Laravel - 在非对象上调用成员函数get()

时间:2014-09-05 09:25:05

标签: php laravel laravel-4

@foreach ($wishItems as $wishItem)
    <?php $products = Product::find($wishItem->product_id)->get(); ?>
    @foreach($products as $product)
        @if($product->id == $wishItem->product_id)
            Name: <a href="{{ URL::route('product', $product->id) }}"> {{ $product->title }} </a><br>
            Price: {{ $product->price }} &euro;<br>
            <hr>
        @endif
    @endforeach
@endforeach

$wishItems是发送到此视图的var并且没关系...... $products = Product::find($wishItem->product_id)->get(); 这里我有问题..我收到错误: {{ 1}} ....我尝试将 Call to a member function get() on a non-object 替换为数字,例如 $wishItem->product_id [它存在于数据库]但是再一次......

2 个答案:

答案 0 :(得分:1)

假设您有一个WishItem和产品型号

class WishItem extends Eloquent {

    public function product()
    {
        return $this->hasOne('Product');
    }

}

在你看来

$product = $wishItem->product;

更多信息:

http://laravel.com/docs/eloquent#basic-usage

答案 1 :(得分:1)

我认为你真正想要的是:

@foreach ($wishItems as $wishItem)
    <?php $product = Product::find($wishItem->product_id); ?>
    Name: <a href="{{ URL::route('product', $product->id) }}"> {{ $product->title }} </a><br>
    Price: {{ $product->price }} &euro;<br>
    <hr>
@endforeach

您的$wishItem实际上只是引用单个产品,因此您无需查询集合,也无需循环。