ai 给出了三个方法 方法1:使用whereRaw实现动态截取匹配 public function modelB() { return $this->hasOne(modelB::class, 'ddd', 'ccc') ->whereRaw('SUBSTRING_INDEX(ccc, "_", 1) = modelB.ddd'); } 方法2:添加访问器动态处理
// ModelA中 public function getCccWithoutSuffixAttribute() { return explode('_', $this->ccc)[0]; }
public function modelB() { return $this->hasOne(modelB::class, 'ddd', 'ccc_without_suffix'); }
方法3:数据库层预处理(需MySQL支持) // 迁移文件 $table->string('ccc_prefix')->virtualAs("SUBSTRING_INDEX(ccc, '_', 1)");
//模型 public function modelB() { return $this->hasOne(modelB::class, 'ddd', 'ccc_prefix'); }
方法1可能影响索引使用效率 方法2需要确保访问器逻辑与业务需求一致 如果关联查询频繁,建议使用方法3
推荐文章: