[英]Laravel Eloquent JOIN over multiple tables
I'm having trouble with a JOIN over 2 tables. 我在加入2张桌子时遇到了麻烦。 One of them isn't associated directly with the Eloquent model 'Message'.
其中之一与雄辩的模型“消息”没有直接关联。
My Tables: 我的桌子:
videos
-- id
-- file
messages
-- m_id
-- m_type
-- m_video
videos_languages
-- video_id
-- language_id
I have the following models: 我有以下型号:
User.php
Video.php
Message.php
Video.php has following relation: Video.php具有以下关系:
public function languages()
{
return $this->belongsToMany('Language','videos_languages','video_id','language_id')->withPivot('titel','vl_id');
}
Message.php Message.php
public function messageVideos()
{
return $this->belongsTo('Video','m_video','id');
}
public function messageUser()
{
return $this->belongsTo('Visitor','m_from','v_id');
}
In my main script, I do the following command: 在主脚本中,执行以下命令:
$message = new Message();
$message->where('m_to','=',12345)->with('messageVideos','messageUser')->first()
So I get the data of Message with the associated tables "Videos" and "User". 因此,我获得了带有关联表“视频”和“用户”的Message数据。
My problem now: I also need videos_languages in this command, and it is not associated with the Message model. 现在的问题是:在此命令中我还需要video_languages,并且它与消息模型没有关联。
Is it possible, to include it within the top command and use the languages() relation from the Video model? 是否可以将其包含在top命令中,并使用Video模型中的language()关系?
I dont think you need "whereHas", but "Eager Load Constraints". 我认为您不需要“ whereHas”,但需要“ Eager Load Constraints”。 This is found under eager loading in the laravel docs.
这可以在laravel文档中的快速加载中找到。
For Example: 例如:
$users = User::with(array('posts' => function($query)
{
$query->where('title', 'like', '%first%');
}))->get();
You however need to nest it and load more relations. 但是,您需要嵌套它并加载更多关系。
So it's like this: 就像这样:
$message = Message::where('m_to','=',12345)
->with(array('messageVideos.languages' => function($query)
{
$query->where('language_id', '=', 2);
},
'messageUser'))->first();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.