Helllo,我想用laravel在两个表之间连接,但是如果表B没有行查询,则返回null。我想要的是这样。
table A
id user_id description
1 1 something
2 1 apple
3 2 cherry
table B
user_id post_id vote
(with no records initial)
result table
id user_id description post_id vote
1 1 something null null
2 1 apple null null
3 2 cherry null null
我怎么能这么做?事先谢谢你,我为英语不好而道歉。
发布于 2020-11-28 09:30:20
你应该使用leftJoin
DB::table("tableA")->leftJoin("tableB","tableA.user_id",'=','tableB.user_id')
->select(["tableA.id as id",'tableA.user_id as user_id','description','post_id','vote'])->get();
发布于 2020-11-28 09:33:20
您可以利用雄辩的关系来获得所需的输出。
Assume Table A is represented by ModelA and Table B is represented by ModelB
class ModelA extends Model
{
//Get all related ModelB records
public function kids()
{
return $this->hasMany(ModelB::class, 'user_id', 'user_id');
}
}
class ModelB extends Model
{
//Get the ModelA record to which the ModelB record belongs
public function parent()
{
return $this->belongsTo(ModelA::class, 'user_id', 'user_id');
}
}
现在您可以在任何地方获取ModelA记录的所有ModelA(相关)记录。
$modelA = ModelA::with('kids')->first();
$modelA->kids //These records will hold values from Table B
或者使用QueryBuilder
$rows = DB::table('TableA')
->leftJoin('TableB', 'TableA.user_id', '=', 'TableB.user_id')
->select('id', 'TableA.user_id', 'description', 'post_id', 'vote');
雄辩或查询生成器是一种选择
发布于 2020-11-28 09:50:41
假设表A是用户模型,表B是Post模型。雄辩的质疑:
$users = User::leftJoin('posts', function($join) {
$join->on('users.id', '=', 'posts.user_id');
})
->whereNull('posts.user_id')
->first([
'users.id',
'users.description',
'posts.id',
'posts.vote'
]);
https://stackoverflow.com/questions/65048096
复制相似问题