O
O
OlexAd2021-04-08 07:21:24
Laravel
OlexAd, 2021-04-08 07:21:24

Laravel many-to-many, why not getting all the data?

There are 3 tables with a configured many-to-many relationship:
Deals (id, bx_id)
Products (id, bx_id)
DealsProducts (id, deal_id, product_id)

For example, 3 records are added through the relationship:

public function products()
    {
        return $this->belongsToMany(Product::class,'product_deal', 'deal_id','product_id', 'BX_ID', 'BX_ID')
            ->using(ProductDeals::class)
            ->withPivot([
                'PRICE',
                'QUANTITY',
                'PRODUCT_NAME',
            ]);
    }

$deal->products()->sync($rows);

But when you try to get these 3 records, only 2 are returned
606e8326a6dce816290637.png

:
// Вернет 2 записи
    $deal = Deal::where('bx_id',15322)->with('products')->firstOrFail();
/***
select * from `products` 
inner join `product_deal` 
on `products`.`BX_ID` = `product_deal`.`product_id` 
where `product_deal`.`deal_id` = ?
 */


// Вернет 3 записи
    $products = DB::table('product_deal')
        ->select('*')
        ->where('product_deal.deal_id', 15322)
        ->get();
/***
select * from `product_deal` 
where `product_deal`.`deal_id` = ?
 */

Laravel Framework 8.26.1

Why is this happening? And how to get all records via link?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question