【问题标题】:I can't make some Eloquent relations to work我无法建立一些 Eloquent 关系来工作
【发布时间】:2016-06-04 19:50:52
【问题描述】:

让我先解释一下我的表的关系,然后我会解释我不能做什么。

所以,我有一个名为“Company”的实体,它有很多“Income”,其中有很多“IncomeUnitSale”,其中有一个“IncomeUnitSaleUnitPrice”

Company 1->* Income 1->* IncomeUnitSale 1->1 IncomeUnitSaleUnitPrice

型号:

公司模式

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

收入模型(表有“company_id”)

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

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

IncomeUnitSale 模型(表有“income_id”)

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

public function IncomeUnitSaleUnitPrice(){
    return $this->hasOne('App\IncomeUnitSaleUnitPrice');
}

IncomeUnitSaleUnitPrice(表有“income_unit_sale_id”)

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

我想要做的是:

$company = Company::where("id","=",1)->first();
$company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice

但它说它为空,它一直有效到$company->Income->IncomeUnitSale,但在那之后不显示任何关系。

谁能告诉我我做错了什么?

谢谢!

【问题讨论】:

    标签: laravel database-design model eloquent database-relations


    【解决方案1】:

    hasMany 关系将始终返回 Eloquent Collection 对象。如果没有相关记录,它将只是一个空的CollectionhasOnebelongsTo 关系将始终返回相关模型,如果没有相关模型,则返回 null

    因为你的一些关系是hasMany,你必须迭代返回的Collection才能走得更远。因此,您必须:

    而不是 $company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice
    foreach($company->Income as $income) {
        foreach($income->IncomeUnitSale as $sale) {
            echo $sale->IncomeUnitSaleUnitPrice->price;
        }
    }
    

    【讨论】:

    • 谢谢!老实说,$company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice 会更好。但这也很有效,谢谢!
    • @mkmnstr 如果您的公司有多个收入,并且每个收入都有多个单位销售价格,您希望$company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice 返回哪个记录?
    • 完全正确。我不知道我在想什么 xD 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2021-02-06
    • 2016-07-03
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多