Using latest Laravel, I have written next query:
$news = DB::table('news_content')
->join('news_permissions', 'news_content.id', '=', 'news_permissions.news_id')
->select('news_content.*')
->whereIn('news_permissions.group_id', $allPGs)
->get();
Using Eloquent with join seems alot of complication. This query returns array of StdClasses, but I would need array of Models, namely NewsContent Models for using it further in Transformer.
Casting like:
foreach($news as $item){
$result[] = (NewsContent)$item;
}
doesnt work, other solutions with custom casting from StdClass to Model seem not optimal.
Is there a better way to get Model out of Laravels DB query? Or shorter casting procedure from StdClass to Model than this suggestions: Convert/cast an stdClass object to another class?
CodePudding user response:
Using Eloquent with join seems alot of complication
why that , you just need to call your query builder throw your model:
$news = NewsContent::join('news_permissions', 'news_content.id', '=', 'news_permissions.news_id')
->select('news_content.*')
->whereIn('news_permissions.group_id', $allPGs)
->get();
please note that Eloquent uses query builder internally in Model.php abstract class:
* @param \Illuminate\Database\Query\Builder $query
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newEloquentBuilder($query)
{
return new Builder($query);
}