Laravel

Laravel 模型关系:一对多

配套视频地址:https://www.bilibili.com/video/av73028135?p=3


一对多:一篇文章可以有多个评论,一个评论只属于一篇文章。


表结构

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

发表评论