1 一对一
一对一关联是一个非常简单的关联关系,例如,一个User模型有一个与之对应的Phone模型。要定义这种模型,我们需要将phone方法置于User模型中,phone方法应该返回Eloquent模型基类上hasOne方法的结果:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model{
/**
* 获取关联到用户的手机
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
2 一对多
“一对多”是用于定义单个模型拥有多个其它模型的关联关系。例如,一篇博客文章拥有无数评论,和其他关联关系一样,一对多关联通过在Eloquent模型中定义方法来定义:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model{
/**
* 获取博客文章的评论
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
www.judyhcm.com
2.3 多对多
多对多关系比hasOne和hasMany关联关系要稍微复杂一些。这种关联关系的一个例子就是一个用户有多个角色,同时一个角色被多个用户共用。例如,很多用户可能都有一个“Admin”角色。要定义这样的关联关系,需要三个数据表:users、roles和role_user,role_user表按照关联模型名的字母顺序命名,并且包含user_id和role_id两个列。
多对多关联通过编写一个调用Eloquent基类上的belongsToMany方法的函数来定义:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model{
/**
* 用户角色
*/
public function roles()
{
return $this->belongsToMany('App\Role');
}
}