dotelauv682684 2017-09-20 07:27
浏览 116
已采纳

Laravel Eloquent查询模型与关系

I have 2 models with a relationship Company and DamageReport.

A DamageReport is always linked to a Company by the key company_id.

So company_id in DamageReport equals id in Company.

Very simple, right? Now my goal is to query the Company when I know the id of the DamageReport.

For example

I have a row of the DamageReport table:

id company_id

6  1

And the record of Company with id is:

id name

1  Company 1

So in my controller I have the DamageReport id (6) and need to query company with id 1.

I've set up a relationship like this in my models

Company model:

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

DamageReport model:

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

Now in my controller I tried something like this but I honestly have no clue

$company = new Company;

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

dd($company);
  • 写回答

3条回答 默认 最新

  • dpl74687 2017-09-20 07:50
    关注

    Your relationship is wrong.

    It should be

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度