Reputation: 253
So i got a bit of a problem here with Laravel relationships.
I have a model for lead conversions and it has a hasOne relationship with a details model, the details model contains a hashkey field that i need to use.
public function details()
{
return $this->hasOne('App\Models\CampaignDetails', 'n_idcampaign', 'n_idcampaign')->select(['n_idcampaign', 'hashkey']);
}
So far so good, i really only need the hashkey but i need to return the idcampaign as well as a foreign key or else it won't work for some reason...
When i query the model i do the following.
return $this->model->with('details')->where('n_idcampaign', 1884)->first();
So far, so good, it returns the whole thing, it's a pain to access it like first()->details->hashkey
but at least it works...
The bigger problem appears when i need to do where queries based on the Hashkey...
return $this->model->with('details')->where('idData', $id)->where('hashkey', $haskkey)->first();
This doesn't work, how can i make it so that i can query the main model based on a field from a relationship (in this case hashkey)
Upvotes: 1
Views: 500
Reputation: 35200
If your need to constrain your query based on a relationship you can use the whereHas()
method.
return $this->model->with('details')
->where('idData', $id)
->whereHas('details', function ($query) use ($haskkey) {
return $query->where('hashkey', $haskkey);
})
->first();
https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence
Hope this helps!
Upvotes: 0