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
this line
$this->product()
, is a relationship query where it pass the main model id to its related model, can be translated to this querywhich 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 thisAlso, I dont think that loop would even work, you should just transform whatever that
$this->get()
is, into a collection, then pluck thecontent_product_id
and usewhereIn
in your query.e.i.
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 RelationshipsThe previous code gets all the products of the first user using the
products
relationship method that must be defined in theUser.php
model such as:As Laravel illustrated in the previous link, Laravel will assume that the
products
table containsuser_id
that will match the value in theid
column of theusers
table.