【问题标题】:Laravel Eloquent: hasManyThrough Many to Many relationshipLaravel Eloquent: hasManyThrough 多对多关系
【发布时间】:2019-03-26 09:03:06
【问题描述】:

我的 Laravel 5.7 模型中有以下类(此处简化):

VEHICLE.PHP

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Vehicle extends Model
{

    public function journeys()
    {
        return $this->hasMany('App\Journey');
    }

}

旅程 PHP

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Journey extends Model
{

    public function vehicle()
    {
       return $this->belongsTo('App\Vehicle');
    }

    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

USER.PHP

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{  

    public function journeys()
    {
        return $this->belongsToMany('App\Journey');
    }
}

我在用户和旅程之间有一个中间表 (journey_user)(请参阅随附的架构)。

我可以轻松获取特定用户的所有旅程。但是我怎样才能获得特定用户使用的所有车辆?由于用户和旅程之间的多对多关系,标准的 hasManyThrough 方法似乎不起作用。

感谢您的帮助!

【问题讨论】:

  • 车辆似乎是旅程的财产——所以最好的办法是经历这种关系。如果您想要一种轻松访问用户在整个旅程中使用的车辆的方法,那么我会为该逻辑创建某种存储库或服务......不在用户模型中。跨度>

标签: php laravel eloquent relationship


【解决方案1】:

我还没有测试过。但是,应该可以通过循环遍历所有userjourneys 来获取所有vehicles,创建一个车辆数组并将其作为collection 返回。

这可以添加到您的User.php 模型控制器中:

/**
 * Get all vehicles which user has used
 *
 */
public function vehicles()
{
    $vehicles = [];

    $this->journeys()
        ->each(function ($journey, $key) use (&$vehicles) {
            $vehicles[] = $journey->vehicle;
        });

    return collect($vehicles);
}

在这里,我们创建一个空数组。然后我们循环遍历用户的所有旅程(传递$vehicles 数组作为引用来更新它)。

我们使用each() 集合方法循环遍历每个journey。我们为$vehicles 数组创建一个新条目,添加vehicle

最后,我们将所有vehicles 作为一个集合返回。

我们可以像这样在我们的应用程序中使用它:

User::find($id)->vehicles();

注意:您可以通过将函数名称更改为setVehiclesAttribute() 将其作为访问器 属性返回。这将允许您访问车辆字段,例如User::find($id)-&gt;vehicle

【讨论】:

  • 欢迎@Mateo!
猜你喜欢
  • 2020-10-14
  • 1970-01-01
  • 2019-06-13
  • 2016-09-26
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
相关资源
最近更新 更多