lundi 18 mars 2019

Check if related model have entry in another related model

i have following models and there relation

Models

User
Product
Orders
OrderProduct
ProductReviews

Relations

User hasMany Orders
Orders hasMany OrderProdut
User hasMany ProductReview
Product hasMany ProductReview
ProductReview belongsTo User

Inside the product page all the reviews for that product is listed with the user details who made the review. I want to check if review in list has made a purchase of the reviewed product.

So far i have done this with php loops and eager loading. Is there a better way to do this

$product = Product::with([
    'reviews'=>function($q) {
        $q->where('status', 1);
    },
    'reviews.user'
])->first();

if($product){
    $product->load(['reviews.user.orders.orderProducts' => function($q) use($product){
        $q->where('product_id',$product->id);
    }]);
}

foreach ($product->reviews as $review){
    $review->purchased_from_microless = false;
    foreach ($review->user->orders as $order) {
        if($order->orderProducts->count()){
            $review->purchased_from_microless = true;
            break;
        }
    }

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire