Laravel 5.1 - 使用WHERE子句检索多态关联

时间:2018-02-13 17:04:40

标签: php sql laravel laravel-5.1 polymorphic-associations

我在检索多态关联时遇到问题"其中related_object.column_name = x"。让我解释一下:

我有很多“页面"在我的数据库中,每个页面都与不同类型的“内容”有多态关联。例如:

页面

slug:my-page,id:1

slug:my-other page,id:2

music_track表

music_track:id 10,page_id:1

视频表

视频:ID 20,page_id:2

图片表

image:id 30,page_id:1

内容表

id:555,contentable_id 10,contentable_type:App \ music_track

id:556,contentable_id 20,contentable_type:App \ video

id:557,contentable_id 30,contentable_type:App \ image

我可以使用Content :: all()返回所有内容,如何返回page_id为'1'的所有内容?

我似乎无法使用Content :: where(' page_id'," ="," 1"),因为page_id不明确,或假设是内容表的一部分。如何查询RELATED表?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

将此方法放在MusicTrackImageVideo模型中:

/**
 * Return a list of related models based on page id
 *
 * @param \Illuminate\Database\Eloquent\Builder $query 
 * @param int $id 
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeOfPage($query, $id)
{
    return $query->where('page_id', $id);
}

然后,如果您拥有Page模型中的所有关系:

$images = $page->images()->ofPage($id)->get();
//
$music_tracks = $page->music()->ofPage($id)->get();
//
$videos = $page->videos()->ofPage($id)->get();

如果你没有,那么:

/**
 * Return a list of images which are included in this page.
 *
 * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
 */
public function images()
{
    return $this->morphToMany('App\Image', 'contentable');
}

/**
 * Return a list of music tracks which are included in this page.
 *
 * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
 */
public function music()
{
    return $this->morphToMany('App\Music', 'contentable');
}

/**
 * Return a list of music tracks which are included in this page.
 *
 * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
 */
public function videos()
{
    return $this->morphToMany('App\Video', 'contentable');
}