无法显示与laravel 5.4雄辩关系的数据

问题描述 投票:1回答:1

我希望在我的视图中显示来自雄辩关系的数据,但我似乎做错了什么。这是我的模型关系,控制器和视图

产品

class Product extends Model
{
    protected $guarded = ['id'];

    public function prices()
    {
        return $this->hasMany(Price::class, 'product_id');
    }
}

价钱

class Price extends Model
{
    protected $guarded = ['id'];

    public function product()
    {
        $this->belongsTo(Product::class);
    }
}

HomeController的

public function index()
{
    $products = Product::with('prices')->get();

    return view('home', compact('products'));
}

视图

@foreach ($products as $product)
<tr>
    <td>{{ $product->prices->date }}</td>
    <td>{{ ucwords($product->name) }}</td>
    <td>{{ $product->prices->cost }}</td>
</tr>
@endforeach

我的视图返回错误Property [date] does not exist on this collection instance如何修复此错误?

php laravel laravel-5 laravel-5.4
1个回答
1
投票

在hasMany关系中,你有一个Collection作为结果,所以你应该有另一个foreach来访问每个Price。尝试这样的事情:

@foreach ($products as $product)
    @foreach ($product->prices as $price)
        <tr>
            <td>{{ $price->date }}</td>
            <td>{{ ucwords($product->name) }}</td>
            <td>{{ $price->cost }}</td>
        </tr>
    @endforeach
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.