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. Laravel
Eloquent
Currently I only found with
method
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!
習慣沉默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
给我你的怀抱2017-05-16 16:53:58
$thread = Thread::with(['comments' => function ($query) {
$query->whereNotNull('user');
}, 'comments.user'])->first();
巴扎黑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.
PHP中文网2017-05-16 16:53:58
\DB::('threads')
->where(['threads.id'=>$id])
->leftJoin("comments",'therads.id','=','comments.tid')
->paginate()
巴扎黑2017-05-16 16:53:58
Just write join in the relationship, ->hasMany()->join()->where(). Write it however you want.
世界只因有你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
里有 preload
、includes
、Eager load
、Joins
, 可以来区别eager loading
Data method.
Here is an article to explain
http://www.mamicode.com/info-...
AndYii
的ActiveRecord
也有with
, joinWith
(inner join, left join ....) innerJoinWith
, 来根据需求做eager loading
I won’t check other things. It’s not that I want to damage laravel
, 我是到现在也没有觉得laravel
的Eloquent
what’s so powerful