vendredi 22 novembre 2019

Laravel with relation returning inaccurate result

I am trying to make a query to get all of the Interviews and get the company name in the companies table. I only want to return the name column in the company table.

I ran a query log and noticed that my relation was returning a weird query.

Laravel Version 6.5.2

What I had originally

$interviews = Interview::select('title', 'slug', 'subtitle', 'posted_date')
                                    ->orderBy('created_at', 'DESC')
                                    ->with(['company' => function($query) {
                                        $query->select('id','name');
                                    }])
                                    ->get();

What I'm using now just to test if the relation was working:

\DB::enableQueryLog();

$interviews = Interview::select('title', 'slug', 'subtitle', 'posted_date')
                                    ->orderBy('created_at', 'DESC')
                                    ->with('company')
                                    ->get();
dd(\DB::getQueryLog());

Company Model:

public function interview() {
        return $this->hasOne('App\Interview', 'company_id', 'id');
    }

Interview Model:

public function company() {
        return $this->belongsTo('App\Company', 'id', 'company_id');
    }

Result:

select `title`, `slug`, `subtitle`, `posted_date` from `interviews` where `interviews`.`deleted_at` is null order by `created_at` desc

select * from `companies` where 0 = 1 and `companies`.`deleted_at` is null

I am trying to figure out why it is returning where 0 = 1 and not the actual model.

Also, is there a way to only return one of the fields like I above?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire