ds08541
2017-01-14 22:14
浏览 51
已采纳

Laravel 5.1调用未定义的方法Illuminate \ Database \ Query \ Builder :: cartItems()

I have the following model and controller but it keeps throwing error:

Call to undefined method Illuminate\Database\Query\Builder::cartItems()

This is my model and controller:

 class Cart extends Model
{
    protected $fillable = [
       'user_id',
       'coupon_id',
    ];

    public function cartItems()
    {
       return $this->hasMany('App\CartItem');
    }

}


use App\Cart;
use App\CartItem;

class CartController extends Controller
{


    public function index()
    {

       $userId = Auth::user()->id;

       $cart =  Cart::where('user_id', '=', $userId); 

       $cartItems = $cart->cartItems()->get();

       //...some other stuff...

       return view('cart.index', compact('cartItems'));
    }

 }
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushu9253 2017-01-14 22:57
    已采纳

    Don't call it as a function:

    $cart =  Cart::where('user_id', '=', $userId)->first(); 
    $cartItems = $cart->cartItems;
    

    Laravel will take care of the rest, and get the items from the database.

    打赏 评论

相关推荐 更多相似问题