Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 5.1-检索与WHERE子句的多态关联_Php_Sql_Laravel_Laravel 5.1_Polymorphic Associations - Fatal编程技术网

Php Laravel 5.1-检索与WHERE子句的多态关联

Php Laravel 5.1-检索与WHERE子句的多态关联,php,sql,laravel,laravel-5.1,polymorphic-associations,Php,Sql,Laravel,Laravel 5.1,Polymorphic Associations,检索多态关联“where related\u object.column\u name=x”时遇到问题。让我解释一下: 我的数据库中有许多“页面”,每个页面都与不同类型的“内容”有多态关联。例如: 页面 我的页面,id:1 我的另一页,id:2 音乐\u曲目表 音乐曲目:id 10,页码:1 视频表 视频:id 20,第2页 图像表 图像:id 30,第1页 内容表 id:555,可满足的\u id 10,可满足的\u类型:App\music\u track id:556,可满足的\u id 2

检索多态关联“where related\u object.column\u name=x”时遇到问题。让我解释一下:

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

页面

我的页面,id:1

我的另一页,id:2

音乐\u曲目表

音乐曲目:id 10,页码:1

视频表

视频:id 20,第2页

图像表

图像:id 30,第1页

内容表

id:555,可满足的\u id 10,可满足的\u类型:App\music\u track

id:556,可满足的\u id 20,可满足的\u类型:App\video

id:557,可满足的\u id 30,可满足的\u类型:App\image

我可以使用content::all()返回所有内容,如何返回页面id为“1”的所有内容


我似乎不能使用Content::where('page_id',“=”,“1”),因为page_id不明确,或者被认为是Content表的一部分。如何查询相关表?

请尝试以下方法:

将此方法放入您的
MusicTrack
Image
Video
型号中:

/**
 * 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);
}
然后,如果您的
页面中有所有关系
模型:

$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');
}

您在模型中定义了所有关系吗?谢谢。这非常聪明,但我想返回$content,其中page_id=$id。上面的结果可以通过Video::where('page_id','=',$id)实现