我有三种模式:
Language
Article
Category
Article
表有两个外键category_id
和Language_id
。语言模型与文章模型具有“一对多”的关系,类似的模型与文章模型具有“一对多”的关系。
我的Category
型号:
class Category extends Model
{
protected $fillable = [
'category_name',
];
public function articles(){
return $this->hasMany('App\Article');
}
}
我的Language
型号:
class Language extends Model
{
protected $fillable = [
'language_name'
];
public function articles(){
return $this->hasMany('App\Article');
}
}
我的Article
型号:
class Article extends Model
{
protected $fillable = [
'language_id','category_id','category_name','article_title',
'article_desc','source_from','source_url','video_link',
'audio_url','author_name','article_image_url','like_count'
];
public function languages(){
return $this->belongsTo('App\Language');
}
public function categories(){
return $this->belongsTo('App\Category');
}
}
如何使用Laravel Eloquent在数据库中插入?
$Article = new Article (
[
'article_image_url' => $img_url ,
'audio_url' => $audio_url,
'category_name'=>$category_name ,
'article_title'=>$request->article_title,
'article_desc'=>$request->article_desc,
'source_from'=>$request->source_from,
'source_url'=>$request->source_url,
'video_link'=>$request->video_link,
'author_name'=>$request->author_name,
'like_count'=>'0',
]
);
$language = new Language;
$category = new Category;
$language->articles()->save($Article);
language_id
没有默认值;这是外键。