【问题标题】:Laravel Eloquent query model with relationship具有关系的 Laravel Eloquent 查询模型
【发布时间】:2018-03-01 03:26:14
【问题描述】:

我有 2 个模型与 Company 和 DamageReport 有关系。

DamageReport 始终通过 key company_id 链接到公司。

因此,DamageReport 中的 company_id 等于 Company 中的 id。

很简单,对吧?现在我的目标是在知道 DamageReport 的 id 后查询 Company。

例如

我有一行 DamageReport 表:

id company_id

6  1

而公司id的记录是:

id name

1  Company 1

所以在我的控制器中,我有 DamageReport id (6),需要查询 ID 为 1 的公司。

我已经在我的模型中建立了这样的关系

公司模式:

/**
 * The Damage Reprots that belong to the Company.
 */
public function damageReports()
{
    return $this->belongsToMany('App\DamageReport');
}

损坏报告模型:

/**
 * The company of a damagereport
 *
 */
public function company()
{
    return $this->belongsTo('App\Company');
}

现在在我的控制器中我尝试了这样的事情,但老实说我不知道​​

$company = new Company;

$company = $company->company($damageReportId);

dd($company);

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    你应该使用:

    $company = DamageReport::find($damageReportId)->company;
    

    说明:

    DamageReport 是您所知道的,因此find($id) 方法将带回您拥有$id 的单个模型。

    由于DamageReport 与Company 的关系设置正确,->company 关系将带回关联的公司模型。

    【讨论】:

      【解决方案2】:

      如果关系是一对多,只需使用belongsTo 和hasMany 方法。

      https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

      所以,您的 DamageReport 模型是正确的,并且在您的 Company 模型中,

      /**
       * The Damage Reprots that belong to the Company.
       */
      public function damageReports()
      {
          return $this->hasMany('App\DamageReport');
      }
      

      那么在你的控制器中,@Skrrp 的答案是对的,

      $company = DamageReport::find($damageReportId)->company;
      

      【讨论】:

        【解决方案3】:

        你们的关系不对。

        应该是

        Company model:
        
        /**
         * The Damage Reprots that belong to the Company.
         */
        public function damageReports()
        {
            return $this->hasMany('App\DamageReport');
        }
        
        
        DamageReport model:
        
        /**
         * The company of a damagereport
         *
         */
        public function company()
        {
            return $this->belongsTo('App\Company');
        }
        
        
        // In your controller
        public function index()
        {
            $damageReportId = 1;
            $company = Company::whereHas('damageReports', function ($q) use($damageReportId) {
                $q->where('id', $damageReportId);
            })->first();
        
            dd($company);
        }
        
        // Or 
        public function index()
        {
            $damageReportId = 1;
            $company = DamageReport::find($damageReportId)->company;
            dd($company);
        }
        

        【讨论】:

          猜你喜欢
          • 2019-11-03
          • 2021-08-22
          • 2013-10-03
          • 2017-07-19
          • 1970-01-01
          • 2016-01-16
          • 2021-08-27
          • 1970-01-01
          • 2016-02-26
          相关资源
          最近更新 更多