Laravel : is this eloquent or query builder join if im using model

Viewed 42

Question 1 : is this eloquent or query builder ?

$q = Topic::from('topic')
    ->join( 'subject', 'subject.id', '=', 'topic.subject_id')
    ->select( 'topic.*',
        'subject.name as subject_name',
        )
    ->get();

Question 2 : if question 1 is eloquent, then is this the right query builder ?

    $q = DB::table('topic')
        ->join( 'subject', 'subject.id', '=', 'topic.subject_id')
        ->select( 'topic.*',
            'subject.name as subject_name',
            )
        ->get();

Question 3 : if in my Topic model, have a function to call topic image path, how do i access it with Query Builder from question 2 ?

is there a better way to access my topic image?

class Topic extends Model
{
    public function image()
    {
        //example
        return $pathImage;
    }
}

thanks if anyone can help me answer my question im confused about the eloquent and query builder

1 Answers

First of all you don't need to use the from('topic') in Eloquent, by calling Topic, eloquent gets the data from topic table, just use:

$q = Topic::join( 'subject', 'subject.id', '=', 'topic.subject_id')
    ->select( 'topic.*', 'subject.name')
    ->get();

Secondly, if the main table is called with the model as above code, in your blade foreach you can just use $q->image() to access whatever you are returning and you can't do that with your second approach which is a query builder.

A better approach would be to create a relationship between Topic and subject in your model, then you can just retrieve subjects like bellow:

$q = Topic::with('subject')->get();

If you don't know how to create relationships in the model, visit: https://laravel.com/docs/9.x/eloquent-relationships

Related