>请参阅我的消息表架构
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->integer('conversation_id')->unsigned()->index();
$table->foreign('conversation_id')->references('id')->on('conversations');
$table->integer('last_sender')->unsigned();
$table->foreign('last_sender')->references('id')->on('users');
$table->string('msg');
$table->integer('deleted')->unsigned();
$table->integer('seen')->unsigned();
$table->timestamps();
});
这是我正在使用的当前查询
Message::whereIn('conversation_id',$msgs)
->with(array('last_sender'=>function($query){
$query->select('id','userName','profilePic', 'firstName','lastName');
}))
->orderBy('conversation_id', 'desc')
->groupBy('conversation_id')
->get();
如您所见,我渴望加载last_sender
.但是我想根据条件加载它。例如,如果用户已登录并且他的 id 为 10 并且last_sender
IS NOT=10,那么我想加载,因为我只想在当前登录用户的 id 不在last_sender
列中时才加载。
任何帮助都非常感谢。谢谢。
Message::with([
'last_sender' => function($q) use ($userId = Auth::user()->id) {
$q->where('id','!=',$userId)
}
])->get();
在条件下急切加载关系。
Message::whereHas(
'last_sender', function($q) use ($userId = Auth::user()->id) {
$q->where('id','!=',$userId)
}
)->get();
加载模型实例(如果它与条件有关系(。
希望这是你要求的?