1

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?

SubjectX
  • 836
  • 2
  • 9
  • 33
  • 1
    Why is it a lot of complication? You literally just need to replace `DB::table('news_content')->` with `NewsContent::` – apokryfos Nov 10 '21 at 08:45
  • No way... I dont know, I missed something.. I'm speechless tbh.. Thank you! I there a way to accept your comment as an answer? – SubjectX Nov 10 '21 at 08:46
  • 1
    Also, why not define the relationship, in that case you can lose the `->join`. – Gert B. Nov 10 '21 at 08:48
  • I have defined relationship $this->hasMany(NewsPermission::class, 'news_content_id'); but how do I get rid of join now? – SubjectX Nov 10 '21 at 09:57

1 Answers1

2

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);
    }
OMR
  • 11,736
  • 5
  • 20
  • 35