Laravel eloquent with how to join query
PHP中文网
PHP中文网 2017-05-16 16:51:58
0
6
1389

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中文网

认证高级PHP讲师

reply all(6)
習慣沉默

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

给我你的怀抱
$thread = Thread::with(['comments' => function ($query) {
    $query->whereNotNull('user');
}, 'comments.user'])->first();
巴扎黑

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.

洪涛

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

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

世界只因有你

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template