我貌似发现一个bug

一对多

一对多关联的例子如,一篇 Blog 文章可能「有很多」评论。可以像这样定义关联:

class Post extends Model {

public function comments()
{
return $this->hasMany('App\Comment');
}

}

现在可以经由动态属性取得文章的评论:

$comments = Post::find(1)->comments; //这里调用的方法即便没有定义,依然不会报错

如果需要增加更多条件限制,可以在调用 comments 方法后面通过链式查询条件方法:

$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();

同样的,您可以传入第二个参数到 hasMany 方法更改默认的外键名称。以及,如同 hasOne 关联,可以指定本身的对应字段:

return $this->hasMany('App\Comment', 'foreign_key');

return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

定义相对的关联

要在 Comment 模型定义相对应的关联,可使用 belongsTo 方法:

class Comment extends Model {

public function post()
{
return $this->belongsTo('App\Post');
}

}
已邀请:

要回复问题请先登录注册