所以我在Laravel关系中遇到了一点问题。
我有一个模型引线转换,它有一个hasOne关系与细节模型,细节模型包含一个哈希键字段,我需要使用。
public function details()
{
return $this->hasOne('App'Models'CampaignDetails', 'n_idcampaign', 'n_idcampaign')->select(['n_idcampaign', 'hashkey']);
}
到目前为止这么好,我真的只需要哈希键,但我需要返回idcampaign以及外键,否则它不会因为某种原因工作…
当我查询模型时,我做以下操作:
return $this->model->with('details')->where('n_idcampaign', 1884)->first();
到目前为止,一切顺利,它返回了整个东西,像first()->details->hashkey
那样访问它有点痛苦,但至少它能工作…
当我需要做基于Hashkey的查询时,出现了更大的问题…
return $this->model->with('details')->where('idData', $id)->where('hashkey', $haskkey)->first();
这不起作用,我怎样才能使它能够从关系中查询基于字段的主模型(在这种情况下hashkey)
如果您需要基于关系约束您的查询,您可以使用whereHas()
方法。
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
希望这对你有帮助!