【问题标题】:Laravel - Call to a member function get() on a non-objectLaravel - 在非对象上调用成员函数 get()
【发布时间】:2014-09-05 17:35:02
【问题描述】:
@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-&gt;product_id)-&gt;get(); 我有问题.. 我收到错误:Call to a member function get() on a non-object .... 我尝试将 $wishItem-&gt;product_id 替换为数字,例如 3 [它存在于数据库中] 但同样...

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案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实际上只是指单个产品,因此您无需查询集合并执行循环。

    【讨论】:

    • 试图获取非对象的属性
    • 它会在$wishItem-&gt;product_id$product 上向您抛出错误。
    • 来自产品...我也尝试用数字替换 $wishItem->product_id 但它是一样的
    • 试试Product::findOrFail($wishItem-&gt;product_id)或者你的号码,如果失败,字面意思就是找不到那个ID的产品
    • 我知道了...是的...我的愿望清单表我有 product_id 3...在产品表中我还没有...:D 谢谢
    【解决方案2】:

    假设你有一个 WishItem 和 Product 模型

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

    在你看来

    $product = $wishItem->product;
    

    更多信息:

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

    【讨论】:

    • 当我删除 get 我得到这个:为 foreach() 提供的参数无效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    相关资源
    最近更新 更多