Laravel检查eloquant-relationship上的一个参数

时间:2017-08-16 12:35:18

标签: php laravel laravel-5 laravel-eloquent

我有三个表,如下面的结构。

表 - 帐户服务

id | service_id| account_id|
----------------------------
 1 | 1         | 8181      |
 2 | 2         | 8181      |
 3 | 3         | 8181      |
 4 | 5         | 8181      |

表: - 服务

 id | Name |
------------
 1 | A     |   
 2 | B     | 
 3 | C     | 
 4 | D     | 

表: - CompletedService

 id | service_id | account_id
------------------------------
 1 | 1           | 8181  
 2 | 1           | 8182
 3 | 1           | 8181
 4 | 2           | 8181

现在我的关系查询在下面。

 $acc = AccountService::with(['service' => function($q) {

                    }])->with(['completedServiceRest' => function($q) {

                    }])->where('account_id', $account_id)->get();

如何根据account_id和service_id获取关系部分的记录。 当前记录显示在completedSericeRest的关系中,其中所有记录的account_id与AccountService表匹配。

当发生这种关系时,请检查已完成的服务中的service_id和account_id,而不仅仅是account_id。

模特之间的关系。

 public function completedServiceRest() {
    return $this->hasMany('App\CompletedService', 'account_id', 'account_id');
}

enter image description here

目前获取的account_id匹配的所有记录不是基于参数service_id和account_id仅影响account_id。

先谢谢。

1 个答案:

答案 0 :(得分:0)

使用另一个结构会更容易,您的表“帐户服务”的一个示例(当然,默认情况下已完成为0):

id | service_id | account_id | completed |
------------------------------------------
1 |      1      |    8181    |     0     |
2 |      2      |    8181    |     1     |

你的主要关系是:

public function accountedServices() 
{
    return $this->hasMany('App\AccountService', 'account_id', 'account_id');
}

检查已完成的服务:

public function completedServiceRest() 
{
    return $services->accountedServices()->where('completed', 1)->get();
}