I am trying to make the following work, it might be bad practice, I am pretty new to Laravel, so please let me know !
I have a model named Files
, those are linked to the Keywords
through a pivot table.
I am running the following code, but I get Undefined variable: keyword_id
as error.
$keyword_ids = array(148, 4);
$files = new Files;
foreach($keyword_ids as $keyword_id)
{
$files = $files->whereHas('keywords', function($query)
{
$query->where('id', '=', $keyword_id);
});
}
Thanks a lot !
You need to use the use
keyword to have your variables accessible inside the closure.
foreach($keyword_ids as $keyword_id)
{
$files = $files->whereHas('keywords', function($query) use ($keyword_id)
{
$query->where('id', '=', $keyword_id);
});
}
You can go without foreach and use whereIn to check if id matches any of $keyword_ids values.
$files = $files->whereHas('keywords', function($query) use ($keyword_ids)
{
$query->whereIn('id', $keyword_ids);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.