Laravel Join关联查询后同名字段取值为关联表数据问题
问题根本原因
replies和topics两张表都存在名为text的字段,当你使用join关联查询且没有显式指定查询字段时,查询结果中同名的text字段会被后关联的topics表的text值覆盖,因此你最终拿到的始终是主题表的字段值。
解决方案
- 方案1:显式指定查询字段,对同名字段设置别名
修改你的查询代码,通过select方法指定需要的字段,同名字段加别名区分:
public function ShowReplies($userid) { $data = DB::table('replies') ->select( 'replies.*', 'topics.id as topic_id', 'topics.text as topic_text', // 其他你需要用到的topics表字段都按需添加,注意避免重名即可 ) ->join('topics', 'topics.id', '=', 'replies.topic') ->where('topics.type', '=', 3) ->where('replies.isPostDeleted', '=', 0) ->where('replies.player', '=', $userid) ->orderBy('replies.id', 'desc') ->get(); return view('replies')->with('data', $data); }
修改后Blade模板中:
取回复表的text值调用
$d->text取主题表的text值调用
$d->topic_text方案2:使用Eloquent模型关联(更推荐)
定义模型关联后用预加载查询,完全避免同名字段冲突问题,代码可维护性更高:
- 定义Reply模型和Topic的关联关系
// app/Models/Reply.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Reply extends Model { public function topic() { return $this->belongsTo(Topic::class, 'topic'); } }
- 修改查询代码
public function ShowReplies($userid) { $data = Reply::with('topic') ->whereHas('topic', function($query) { $query->where('type', 3); }) ->where('isPostDeleted', 0) ->where('player', $userid) ->orderBy('id', 'desc') ->get(); return view('replies')->with('data', $data); }
修改后Blade模板中:
- 取回复表的text值调用
$d->text - 取主题表的text值调用
$d->topic->text
内容的提问来源于stack exchange,提问作者Freezy
相关产品推荐
相关产品推荐

