具有多通关系
Has-Many-Through Relations
我在 Google 中对此进行了大量研究。在模型之间使用这种类型的关系没有很好的例子。
有人可以在 Laravel 中使用 Has-Many-Through 关系分享自己的样本吗?
让我们以您拥有用户、他们的朋友和他们朋友的照片的社交网络为例。 3个模型。是的,朋友只是一个普通用户,但对于这个例子,朋友将是一个单独的模型。
1- 用户有朋友
public function friends() {
return $this->hasMany(Friend::class);
}
2 - 朋友有照片
public function photos() {
return $this->hasMany(Photo::class);
}
3 - 你是管理员。你有很多用户,包括 John。约翰有很多朋友。所以有时候,您想查看 John 朋友的照片,也许是他们标记他的那些照片。所以在用户中你定义了关系
public function friendsPhotos() {
return $this->hasManyThrough(Friend::class, Photo::class); //could add a scope here for picture with tags only.
}
可能不是最好的例子。但它显示了如何通过
来查看 John 的所有朋友图片
$john = User::where('email', 'john@email.com')->first();
$john->friendsPhotos();
如果这个例子不适合您,现在想想一家银行在特定分行寻找他们最好的销售人员。一个分店有很多销售员,每个销售员有很多他们打交道的客户。
在 Branch 模型中,您定义
public function customers() {
return $this->hasManyThrough(Salesperson::class, Customer::class);
}
希望对您有所帮助。
银行系统的数据库表
1- 分支
id
name
...
2 - 销售人员
id
branch_id
firstname
...
3 - 客户
id
salesperson_id
firstname
...
我在 Google 中对此进行了大量研究。在模型之间使用这种类型的关系没有很好的例子。
有人可以在 Laravel 中使用 Has-Many-Through 关系分享自己的样本吗?
让我们以您拥有用户、他们的朋友和他们朋友的照片的社交网络为例。 3个模型。是的,朋友只是一个普通用户,但对于这个例子,朋友将是一个单独的模型。
1- 用户有朋友
public function friends() {
return $this->hasMany(Friend::class);
}
2 - 朋友有照片
public function photos() {
return $this->hasMany(Photo::class);
}
3 - 你是管理员。你有很多用户,包括 John。约翰有很多朋友。所以有时候,您想查看 John 朋友的照片,也许是他们标记他的那些照片。所以在用户中你定义了关系
public function friendsPhotos() {
return $this->hasManyThrough(Friend::class, Photo::class); //could add a scope here for picture with tags only.
}
可能不是最好的例子。但它显示了如何通过
来查看 John 的所有朋友图片$john = User::where('email', 'john@email.com')->first();
$john->friendsPhotos();
如果这个例子不适合您,现在想想一家银行在特定分行寻找他们最好的销售人员。一个分店有很多销售员,每个销售员有很多他们打交道的客户。
在 Branch 模型中,您定义
public function customers() {
return $this->hasManyThrough(Salesperson::class, Customer::class);
}
希望对您有所帮助。
银行系统的数据库表
1- 分支
id
name
...
2 - 销售人员
id
branch_id
firstname
...
3 - 客户
id
salesperson_id
firstname
...