laravel Eloquent 模型 一对多

一个「一对多」关联用于定义单个模型拥有任意数量的其它关联模型。例如,一篇博客文章可能会有无限多个评论。就像其它的 Eloquent 关联一样,可以通过在 Eloquent 模型中写一个函数来定义一对多关联

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
/**
* 获取这篇博文下的所有评论。
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}

$comments = App\Post::find(1)->comments;

foreach ($comments as $comment) {
//
}

一对多(反向关联)
现在我们已经能访问到所有文章的评论,让我们来接着定义一个通过评论访问所属文章的关联。若要定义相对于 hasMany 的关联,可在子级模型定义一个叫做 belongsTo 方法的关联函数:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
/**
* 获取该评论所属的文章模型。
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
一旦关联被定义之后,则可以通过 post 的「动态属性」来获取 Comment 模型相对应的 Post 模型:

$comment = App\Comment::find(1);

echo $comment->post->title;

文章来自 www.96net.com.cn

posted @ 2022-02-08 13:50  学无边涯  阅读(148)  评论(0编辑  收藏  举报