Chan Chan - 5 months ago 27
PHP Question

A shopping cart ORM check in Laravel

This is my table structure

users


id
username
password


orders


id
user_id


order_details


id
product_id
order_id


And the relationship is all set

User.php

function orders() {
return $this->hasMany('Order');
}


Order.php

function details() {
return $this->hasMany('OrderDetail');
}


OrderDetail.php

I got user id and product id, I want to check if the user bought this product

User::find($userId)->orders()->details()->where('product_id', $productId)->count()
will be wrong, because orders return more than one data, how to do the check?

Answer

You can't do it with one swipe with Eloquent yet. But you can easily write a function like this to do the check:

public function hasBoughtProduct($product_id, $user_id)
{

$orders = Orders::with('details')->where('user_id','=',$user_id)->get();

foreach($orders as $order)
{
    $details = $order->details()->where('product_id', '=', $product_id)->count();
    if($details > 0)
    {
          return TRUE;
    }    
}
return FALSE;
}

If this is not efficient enough for your needs, you might consider using Fluent to write the query or override the newQuery() method where you will pre-join the tables. If this suits you more, you can refer to this answer for more details on how to do it: http://stackoverflow.com/a/19183957/385402