[英]Laravel scope with two relations
我有一个主表“ help_pages”,其中存储了文章或视频的ID。 还有另外两个表格:“文章”和“视频”。
在下面的示例中,对于我的应用程序,$ portalType是'reseller'或'global'。 只要我在要发布的视频上没有标记,一切就很好。 现在,我无法通过发表的文章和视频来过滤范围函数。
这是在我的模型/HelpPage.php中:
public function scopeByPortalType($query, $portalType) {
return $query->where('portal_type', '=', $portalType)
->leftjoin('articles', 'content_id', '=', 'articles.id')
->where('articles.published', '=', '1');
}
我希望我能做的只是增加一秒钟
->leftJoin('videos', 'content_id', '=', videos.id')
->where('videos.published', '=', '0');
但这会返回太多行。 我尝试用UNION为文章和视频创建一个临时表:
CREATE TEMPORARY TABLE IF NOT EXISTS tmp_assets AS
(SELECT id, 'Article' AS content_type FROM articles WHERE published = 1)
UNION
(SELECT id, 'Video' AS content_type FROM videos WHERE published = 1)
然后加入,但没有骰子。 这可能比我做的要小,但是现在我迷路了!
Laravel 4.2版
好吧,这不是完美的,但是它可以满足我的需要:
public function scopeByPortalType($query, $portalType) {
$q = $query
->whereRaw("
(id IN (SELECT help_pages.id FROM help_pages INNER JOIN articles ON content_id=articles.id WHERE articles.published='1' AND content_type='Article')
OR
id IN (SELECT help_pages.id FROM help_pages INNER JOIN videos ON content_id=videos.id WHERE videos.published='1' AND content_type='Video'))")
->where('portal_type', '=', $portalType);
return $q;
}
我希望我能找到一种使用实际Eloquent的方法,但是每一步都使我陷入了一个死胡同的兔子洞。 这工作了!
雄辩的方法是建立关系,这样您就可以利用热切的加载。
关系: http : //laravel.com/docs/4.2/eloquent#relationships
渴望加载: http : //laravel.com/docs/4.2/eloquent#eager-loading
设置关系:
class HelpPage extends Eloquent {
public function articles()
{
return $this->hasMany('Article');
}
public function videos()
{
return $this->hasMany('Video');
}
}
然后,您可以像这样利用紧急加载:
$help_pages = HelpPage::with(array('articles' => function($query)
{
$query->where('published', '=', 1);
},
'videos' => function($query)
{
$query->where('published', '=', 1);
}
))->get();
然后,您也许可以在实际查询中利用whereHas和orWhereHas而不是上面的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.