如何在laravel渴望加载内使用条件

时间:2017-07-31 14:51:42

标签: php laravel eloquent laravel-5.4

请参阅我的消息表架构

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 = 10,那么我想加载,因为我只想加载{{1当前登录用户的id不存在列。

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

Message::whereHas(
  'last_sender', function($q) use ($userId = Auth::user()->id) {
    $q->where('id','!=',$userId)
  }
)->get();

在条件下急切加载关系。

ALTER TABLE tablename AUTO_INCREMENT = 1

加载模型实例,如果它与条件有关系。

希望这是你要求的?

相关问题