有很多关系

时间:2017-02-28 21:33:29

标签: laravel laravel-5.3 laravel-5.4

我在Google上做了很多关于此的研究。在模型之间使用这种类型的关系没有很好的例子。

有人可以在Laravel中使用Has-Many-Through关系分享自己的样本吗?

1 个答案:

答案 0 :(得分:1)

让我们来看一个社交网络的样本,其中包含用户,他们的朋友和朋友的照片。 3个型号。是的,朋友只是普通用户,但对于这个例子,朋友将是一个单独的模型。

1-用户有朋友

public function friends() {
    return $this->hasMany(Friend::class);
}

2 - 朋友有照片

public function photos() {
    return $this->hasMany(Photo::class);
}

3 - 你是管理员。你有很多用户,包括约翰。约翰有很多朋友。所以有时候,你想要看到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();

如果这个例子不适合你,现在想想一家银行在特定分行寻找最好的销售人员。分公司有许多销售人员,每个销售人员都有许多客户与他们打交道。

在分支模型中,您可以定义

public function customers() {
    return $this->hasManyThrough(Salesperson::class, Customer::class);
}

我希望这会有所帮助。

银行系统的数据库表

1-分支

id
name
...

2 - 销售人员

id
branch_id
firstname
...

3 - 客户

id
salesperson_id
firstname
...
相关问题