16. Laravel 模型关系:一对多
Laravel 模型关系:一对多
一对多:一篇文章可以有多个评论,一个评论只属于一篇文章。
表结构
# articles: id, title, content
# comments: id, content, article_id
模型配置
// App\Article
public function comments(){
return $this->hasMany('App\Comment');
}
// App\Comment
public function article(){
return $this->belongsTo('App\Article');
}
使用
增
$article = App\Article::find(1);
$article->comments()->create(['content' => '上海在哪儿']);
删
$article = App\Article::find(1);
$article->comments()->delete();
改
$comment = App\Comment::find(11);
$article = App\Article::find(1);
$comment->article()->associate($article);
$comment->save();
$comment = App\Comment::find(1);
$comment->article()->update(['title' => '广州在哪儿']);
查
$comments = App\Article::find(1)->comments;
$comments = App\Article::find(1)->comments()->where('content', 'like', '%教学%')->get();
$article = App\Comment::find(1)->article;
// 延迟加载
App\Ariticle::with('comments')->find([1,2])
定制模型
指定 comments 表中的外键字段名称
# articles: id, title, content
# comments: id, content, arti_id
// App\Article
public function comments(){
return $this->hasMany('App\Comment', 'arti_id');
}
指定 comments 表中的外键对应 articles 表中的字段名称
# articles: id, title, content
# comments: id, content, article_title
// App\Article
public function comments(){
return $this->hasMany('App\Comment', 'article_title', 'title');
}