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

时间:2017-08-07 20:12:14

标签: php laravel laravel-5 laravel-5.4

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

产品

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 我该如何解决这个错误?

1 个答案:

答案 0 :(得分:1)

在hasMany关系中,您有一个Collection作为结果,因此您应该有另一个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 。尝试这样的事情:

ionic cordova platform rm android
ionic cordova platform add android