Laravel 模型关联关系

一对一

建立关联关系

通过hasOne方法定义一对一关联

public function profile()
{
	return $this->hasOne(UserProfile::class);
}

Eloquent 底层约定

hasOne方法参数

public function hasOne($related, $foreignKey = null, $localKey = null)

第一个参数是关联模型的类名,第二个参数是关联模型类所属表的外键,第三个参数是关联表的外键关联到当前模型所属表的哪个字段。

建立相对的关联关系

通过belongsTo方法来建立相对的一对一关联关系。

public function user()
{
	return $this->belongsTo(User::class);
}

belongsTo方法参数

public function belongsTo($related,$foreignKey = null, $ownerKer = null, $relation = null)

第一个参数是关联模型的类名。第二个参数是当前模型类所属表的外键,第三个参数是关联模型类所属表的主键,第四个参数默认约定是关联关系方法名,也是关联关系动态属性名。

一对多

建立关联关系

通过hasMany方法实现

public function posts()
{
	return $this->hasMany(Post::class);
}

懒加载

通过with方法实现

$post = Post::with('author')
	->where('views','>',0)
	->get();

多对多

建立关联关系

通过belongsToMany方法实现

public function tags()
{
	return $this->belongsToMany(Tag::class,'post_tags');
}

底层约定

belongsToMany方法参数如下

public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null, $relation = null)

第一个参数是关联模型的类名。第二个参数是中间表,第三个参数是中间表中当前模型类的外键,第四个参数是中间表当前关联模型类的外键,第五个参数表示对应当前模型的哪个字段,第六个参数表示对应关联模型的哪个字段,最后一个参数表示关联关系名称,默认是关联方法名。

获取中间表字段

通过with方法传入字段然后将其返回:

public function tags()
{
	return $this->belongsToMany(Tag::class,'post_tags')->withPivot('user_id')->withTimestamps();
}

远程一对多关联

远程一对多是借助中间表进行关联。

建立远程一对多关联关系

通过hasManyThrough方法定义

public function posts()
{
	return $this->hasManyThrough(Post::class,User::class);
}

第一个参数是关联的模型类,第二个参数是中间借助的模型类。

底层约定

hasManyThrough方法的方法参数

public function hasManyThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null)

第一个参数是关联模型类,第二个参数是中间模型类,第三个参数是中间模型类与当前模型类的关联外键,第四个参数指的是中间模型类与关联模型类的关联外键,第五个参数是当前模型类的主键,第六个参数是中间模型类的主键。

定义相对的关联关系

public function image()
{
	return $this->morphOne(Image::class,'imageable');
}

一对多的多态关联

一对多多态关联与一对一类似。

在模型类中构建一对多多态关联

通过morphTo方法定义

public function commentable()
{
	return $this->morphTo();
}

定义相对的关联关系

通过morphMany方法实现

public function comments()
{
	return $this->morphMany(Comment::class,'commentable');
}

多对多的多态关联

通过morphedByMany方法实现

public function posts()
{
    return $this->morphedByMany(Post::class, 'taggable');
}

morphedByMany方法完整参数如下

public function morphedByMany($related, $name, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null)

第一个参数表示关联的模型类,第二个参数表示关联名称,第三个参数表示中间表名称,第四个参数表示当前模型类在中间表的外键,第五个参数表示中间表中的关联ID字段,第六个参数表示当前模型类的主键,第七个参数表示关联模型类的主键。

定义相对的关联关系

morphToMany方法实现

public function tags()
{
    return $this->morphToMany(Tag::class, 'taggable');
}

猜你喜欢

转载自www.cnblogs.com/bigcola/p/13394641.html
今日推荐