laravel Eloquent 关系使用 Distinct
laravel Eloquent relationship using Distinct
我需要使用 DISTINCT 显示具有关系的数据。
这是我的 sql 数据:
table 手袋
id |
49 |
table 行程
id | formateurs_id | pochettes_id
1 | 3 | 49
2 | 4 | 49
3 | 3 | 49
table 业余爱好者
id |
3 |
4 |
型号手拿包
public function Journees()
{
return $this->hasMany('App\Journee','pochettes_id');
}
模型旅程
public function Formateurs()
{
return $this->belongsTo('App\Formateur', 'formateurs_id');
}
我使用此代码来显示不同 formateur 的数据,因为 Formateur 可以在同一个 Pochette 中有多个 Journee :
$pochette = Pochette::find(49);
foreach ($pochette->Journees->distinct('formateurs_id') as $formateur) {
echo $formateur->formateurs_id;
echo "<br>";
}
但是这段代码不起作用,我有这个错误信息
**BadMethodCallException in Macroable.php line 81:
Method distinct does not exist.**
我会显示这个结果:
3
4
不是:
3
4
3
当您访问像 属性 这样的 Eloquent 关系时,您将获得一个 Eloquent Collection. However, distinct()
is a Query Builder 方法,并且您需要在返回集合之前访问查询生成器实例。如果将 ()
添加到关系的末尾,您将获得对 Query Builder 实例的访问权限,并可以链接那些 Query Builder 方法。在你的例子中,你实际上是在寻找 groupBy()
方法而不是 distinct()
。不要忘记以 get()
.
结束查询
foreach ($pochette->Journees()->groupBy('formateurs_id')->get() as $formateur) {
echo $formateur->id ;
echo "<br>";
}
我需要使用 DISTINCT 显示具有关系的数据。
这是我的 sql 数据:
table 手袋
id |
49 |
table 行程
id | formateurs_id | pochettes_id
1 | 3 | 49
2 | 4 | 49
3 | 3 | 49
table 业余爱好者
id |
3 |
4 |
型号手拿包
public function Journees()
{
return $this->hasMany('App\Journee','pochettes_id');
}
模型旅程
public function Formateurs()
{
return $this->belongsTo('App\Formateur', 'formateurs_id');
}
我使用此代码来显示不同 formateur 的数据,因为 Formateur 可以在同一个 Pochette 中有多个 Journee :
$pochette = Pochette::find(49);
foreach ($pochette->Journees->distinct('formateurs_id') as $formateur) {
echo $formateur->formateurs_id;
echo "<br>";
}
但是这段代码不起作用,我有这个错误信息
**BadMethodCallException in Macroable.php line 81:
Method distinct does not exist.**
我会显示这个结果:
3
4
不是:
3
4
3
当您访问像 属性 这样的 Eloquent 关系时,您将获得一个 Eloquent Collection. However, distinct()
is a Query Builder 方法,并且您需要在返回集合之前访问查询生成器实例。如果将 ()
添加到关系的末尾,您将获得对 Query Builder 实例的访问权限,并可以链接那些 Query Builder 方法。在你的例子中,你实际上是在寻找 groupBy()
方法而不是 distinct()
。不要忘记以 get()
.
foreach ($pochette->Journees()->groupBy('formateurs_id')->get() as $formateur) {
echo $formateur->id ;
echo "<br>";
}