laravel 模型关联

一对一  hasOne (用户->手机号)   ->withDefault();  返回指定默认对象

public function phone()
    {
        return $this->hasOne('App\Phone', 'user_id', 'id');
    }
public function user(){
    return $this->belongsTo('App\User', 'user_id', 'id');
}
public function user()
{
    return $this->belongsTo('App\User', 'user_id', 'id')->withDefault();
}

一对多  hasMany (文章->评论)  还可以加上orderBy、where等查询

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

一对多逆向  beloingsTO  (评论->文章)

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

多对多  belongsToMany (用户->角色)

这种关系需要三张数据表:users、roles、role_user,其中role_user表按照关联模型名的字母顺序命名,并且包含user_id和role_id两个列。

/**
     * 用户角色
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'id');
    }

获取中间表字段

正如你已经了解到的,处理多对多关联要求一个中间表。Eloquent 提供了一些有用的方法来与这个中间表进行交互,例如,我们假设 User 对象有很多与之关联的 Role 对象,访问这些关联关系之后,我们可以使用这些模型上的 pivot 属性访问中间表:

$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}

远层一对多 hasManyThrough  (国家->作者->文章)

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string
class Country extends Model{
    /**
     * 获取指定国家的所有文章
     */
    public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\User');
    }
}

上面:第一个传递到 hasManyThrough 方法的参数是最终我们希望访问的模型的名称,第二个参数是中间模型名称。

多态关联  morphMany  (文章/视频 -> 评论)

多态多对多 morphTOMany (文章/视频 -> 标签)

参考:https://laravelacademy.org/post/8867.html#toc_2

猜你喜欢

转载自blog.csdn.net/u011323949/article/details/85273285