class Lesson extends Model
{
public function contentable()
{
return $this->morphTo();
}
}
一堂课只能有其中一种类型的文章
class Video extends Model
{
//
}
class Audio extends Model
{
//
}
class Article extends Model
{
//
}
现在,当我可以使用以下方式将这些模型之一保存为课程内容时:
$lesson->contentable()->associate($articleModel)->save();
$lesson->contentable()->associate($videoModel)->save();
contentable
关系时,该怎么做:Lesson::with(['contentable' => function ($query) {
if ($contentType === Video::class) {
$query->where('status', 1); // on 'videos' table, return a video where status == 1
}
if ($contentType === Article::class) {
// no constraints here.. how to simply return the article?
}
}])->where('id', $lessonID)->firstOrFail();