gpt4 book ai didi

php - 遥远的HasManyThrough

转载 作者:行者123 更新时间:2023-11-29 03:34:06 25 4
gpt4 key购买 nike

我有四个模型:

  1. 用户
  2. 客户
  3. 商店
  4. 机会

关系定义如下:

  • 用户有多个客户端
  • 客户有许多商店
  • 商店有很多机会
  • 用户 hasManyThrough Store,客户端(有效)

问题是我试图通过内置的 Laravel 关系访问 User->Opportunity 关系,但如果没有自定义查询或机会上的附加 user_id 列,我似乎无法做到这一点表以允许直接访问(即使可以从 Store->Client 关系中推断出一个)。如果可以避免的话,我也不喜欢嵌套的 foreach 循环。

我的问题:

在这种情况下,有没有一种方法可以更深入地直接访问用户的商机?实际Model代码及所有相关关系如下:

用户

class User extends Eloquent{
public function clients(){
return $this->hasMany('Client');
}
public function stores(){
return $this->hasManyThrough('Store', 'Client');
}
public function proposals(){
return $this->hasMany('Proposal');
}
public function opportunities(){ //This does the job, but I feel like it could be better
return Opportunity::join('stores', 'stores.id', '=', 'opportunities.store_id')->
join('clients', 'clients.id', '=', 'stores.client_id')->
join('users', 'users.id', '=', 'clients.user_id')->
select('opportunities.*')->
where('users.id', $this->id);
}
public function getOpportunitiesAttribute(){ //This just helps mimic the hasManyThrough shorthand
return $this->opportunities()->get();
}
}

客户端

class Client extends Eloquent{
public function stores(){
return $this->hasMany('Store');
}
public function user(){
return $this->belongsTo('User');
}
public function opportunities(){
return $this->hasManyThrough('Opportunity', 'Store');
}
}

商店

class Store extends Eloquent {
public function client(){
return $this->belongsTo('Client');
}
public function opportunities(){
return $this->hasMany('Opportunity');
}
}

机会

class Opportunity extends Eloquent {
public function store(){
return $this->belongsTo('Store');
}
}

最佳答案

我不认为在 Laravel 中有这样的方法。您必须创建自定义查询。此自定义查询可能非常昂贵,因为将执行多个查询。因此,根据我的说法,最佳解决方案是将用户和机会与外键相关联。

但是,如果您不想使用外键链接 User 和 Opportunity,则可以创建自定义查询来处理此问题。只需在 Opportunity 和 Client 模型之间添加一个“hasManyThrough”关系,例如,

    <?php
class Client extends Eloquent{
public function store(){
return $this->hasMany('Store');
}
public function user(){
return $this->belongsTo('User');
}

public function opportunity(){
return $this->hasManyThrough('Opportunity', 'Store');
}
}

然后在用户模型中创建一个静态函数。

    <?php

class User extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

public function client(){
return $this->hasMany('Client');
}
public function store(){
return $this->hasManyThrough('Store', 'Client');
}

public static function getOpportunityOfUser($userId)
{
$clients = User::find($userId)->client;

foreach ($clients as $client) {
$opportunities[] = Client::find($client->id)->opportunity;
}

return $opportunities;
}
}

现在您可以一次性访问为用户提供的机会,例如,

    Route::get('/', function()
{
return $usersOpportunities = User::getOpportunityOfUser(1);
});

这将返回与 ID 为“1”的用户相关的所有客户的所有机会。

关于php - 遥远的HasManyThrough,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25938081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com