簡體   English   中英

將屬性添加到 eloquent model

[英]Add attribute to eloquent model

我想計算 model 中某個屬性的值,但無法獲得我需要的數據。

class Product extends Model
{

    protected $appends = ['lowest_price'];

    public function shops(){
        return $this->belongsToMany('App\Shop')->withPivot('price','url');
    }

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

    public function getLowestPriceAttribute()                      <-----------------------------
    {
        $lowest_price = 0;
        foreach($this->shops() as $shop) {
            if($lowest_price > $shop->pivot->price) {
                $lowest_price = $shop->pivot->price;
            }
        }
        return $lowest_price;
    }
}

$this->shops()似乎沒有加載我進行計算所需的所有數據。

在我看來,我可以像這樣迭代產品的商店:

@foreach($shops as $shop)   
    <tr>
        <a href="{{ $shop->pivot->url }}" target="_blank">      
            <td>{{ $shop->name }}</td>
            <td>{{ $shop->pivot->price }}EUR</td>
        </a>        
    </tr>
@endforeach

如果這是不可能的,最好的選擇是在視圖本身而不是 model 中進行計算?

您肯定可以在訪問器 function 中執行此操作。 我認為您遇到的問題比您想象的要簡單。

您認為$shops可能是一個集合,但$this->shops()返回一個 Query Builder 實例。所以嘗試在 function 中更改此行:

foreach($this->shops() as $shop) {

有了這個:

foreach($this->shops as $shop) {

讓我知道它是否有效。 沒有() shops將是一個集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM