search

Home  >  Q&A  >  body text

Laravel eloquent with how to join query

Assumption

thread(post) Preload comments(comments) and comments.user(commented user)

Usually one line of code can get it

$thread = Thread::with('comments', 'comments.user')->first();

There is no problem with this, and it can be queried and displayed very well.

$comment = $thread->comments[0]; // Comment Model
$user = $comment->user; // User Model

But the current demand is: if a user data that has commented is deleted, the naturally related comment data cannot be displayed, otherwise the information will be incomplete (is this a normal demand, right?)

According to logic, as long as inner join query can filter out the data that does not match.
LaravelEloquent Currently I only found withmethod

This requirement can be easily solved by ActiveRecord of Yii

$thread = Thread::find()->innerJoinWith(['comments', 'comments.user'])->one();

Laravel I am not very familiar with it, so I would like to ask an expert in this field how to solve it. Thank you!

PHP中文网PHP中文网2797 days ago1384

reply all(6)I'll reply

  • 習慣沉默

    習慣沉默2017-05-16 16:53:58

    The join in the query builder in laravel defaults to the behavior of inner join, the manual says so

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 16:53:58

    $thread = Thread::with(['comments' => function ($query) {
        $query->whereNotNull('user');
    }, 'comments.user'])->first();

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 16:53:58

    Eloquent ORM does not have direct join query conditions, but there are workarounds, as mentioned above.
    But I generally don’t use ORM because of performance reasons. I use Query Builder.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 16:53:58

    
    \DB::('threads')
           ->where(['threads.id'=>$id])
           ->leftJoin("comments",'therads.id','=','comments.tid')
           ->paginate() 

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 16:53:58

    Just write join in the relationship, ->hasMany()->join()->where(). Write it however you want.

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-16 16:53:58

    Actually, what I am asking is mainly about usage. This kind of demand is very common. I am mainly asking if there are any questions in this regard

    This is hererails里都是有实现的
    laravel 目前我看到的只有一个with

    rails里有 preloadincludesEager loadJoins, 可以来区别eager loadingData method.
    Here is an article to explain
    http://www.mamicode.com/info-...

    AndYiiActiveRecord也有with, joinWith(inner join, left join ....) innerJoinWith, 来根据需求做eager loading

    I won’t check other things. It’s not that I want to damage laravel, 我是到现在也没有觉得laravelEloquentwhat’s so powerful

    reply
    0
  • Cancelreply