[英]Insert default values from parent Model in HasMany relationship definition laravel
I have a Lesson Model like this : 我有一个像这样的课程模型:
class Lesson extends Model
{
use SoftDeletes;
public $primaryKey = 'lesson_id';
.
.
.
public function contents ()
{
return $this->hasMany('App\Content', 'lesson_id', 'lesson_id');
}
}
And in other hand Content Model is like : 另一方面内容模型如下:
class Content extends Model
{
public $primaryKey = 'content_id';
public $timestamps = false;
public function lesson ()
{
return $this->belongsTo('App\Lesson', 'lesson_id', 'lesson_id');
}
}
As you see is a hasMany relationship between two model. 如您所见,两个模型之间存在hasMany关系。
Content Model has this attributes : 内容模型具有以下属性:
content_id
lesson_id
contentable_id
contentable_type
order
and Lesson Model has these : 和课程模型有这些:
lesson_id
title
content
Now I want when saving contents of a specific lesson ,some Content Attributes automatically be filled based on Lesson Model attributes. 现在我想在保存特定课程的内容时,会根据课程模型属性自动填充一些内容属性。
$lesson = Lesson::findOrFail($lessonID);
$lesson->contents()->create(
[
'contentable_id' => $newUnit['unit_id'],
]
);
for example lesson_id
of selected lesson be saved as lesson_id
of Content Model and App\\Lesson
string as contentable_type
. 例如,所选课程的
lesson_id
将保存为Content Model的lesson_id
和App\\Lesson
字符串作为contentable_type
。
How Can I do that? 我怎样才能做到这一点?
Do the changes below 进行以下更改
Lesson model 课程模型
class Lesson extends Model
{
use SoftDeletes;
public $primaryKey = 'lesson_id';
.
.
.
public function contents ()
{
return $this->hasMany('App\Content', 'content');
}
}
Content model 内容模型
class Content extends Model
{
public $primaryKey = 'content_id';
public $timestamps = false;
public function lesson ()
{
return $this->belongsTo('App\Lesson', 'content');
}
}
Then try it 然后尝试一下
$lesson = Lesson::findOrFail($lessonID);
$content = new Content();
$content->contentable_id = '1111';
$lesson->contents()->save(content);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.