skip to Main Content

I use Laravel 10.
I try to fetch some data from my mariaDB with the following condition.

  $contentList = $this->get();
        foreach($contentList as $content){
            $this->product()->where('id', '=', $content->content_product_id)->ddRawSql();
        }

But the query I get is:

 select * from `radio_content_products` where `radio_content_products`.`id` is null and `id` = 3

The value of the id is correct, but by big question is: Why there is this `radio_content_products`.`id` is null in my condition?

2

Answers


  1. this line $this->product(), is a relationship query where it pass the main model id to its related model, can be translated to this query

    select * from `radio_content_products` where `radio_content_products`.`id` is null
    

    which appears to be that your $this model is passing null ID for whatever reason you are doing (maybe the way you are dumping the query does not have valid $this model)

    the second line ->where('id', '=', $content->content_product_id) is equal to this

    and `id` = 3
    

    Also, I dont think that loop would even work, you should just transform whatever that $this->get() is, into a collection, then pluck the content_product_id and use whereIn in your query.

    e.i.

    $this->product()
        ->whereIn('id', collect( $this->get() )->pluck('content_product_id') )
        ->get();
    
    Login or Signup to reply.
  2. I wondering about adding a where clause to the relationship. You can just write the next single line of code as illustrated also in Laravel Relationships

    $products = AppModelsUser::first()->products;
    

    The previous code gets all the products of the first user using the products relationship method that must be defined in the User.php model such as:

    // AppModelsUser.php
    
    public function products(): HasMany
    {
       return $this->hasMany(Product::class, 'user_id', 'id');
    }
    

    As Laravel illustrated in the previous link, Laravel will assume that the products table contains user_id that will match the value in the id column of the users table.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search