Laravel Eloquent获得与keyBy的关系 [英] Laravel Eloquent get relationship with keyBy
问题描述
我有一个具有hasMany
关系的Product
模型
I have a Product
model with a hasMany
relationship
public function pricing()
{
return $this->hasMany('App\ProductPrice', 'prod_id', 'id');
}
然后我得到了关系
Product::with('pricing')->all();
如何使用id
作为键来检索pricing
关系.我知道我可以在Collection
和keyBy('id)
上执行此操作,但不适用于查询.
How can I retrieve the pricing
relationship with the id
as the key. I know I can do it on a Collection
with keyBy('id)
but it doesn't work on a query.
我想获得与以下相同的结果,但是我想从Product
关系中得到它.
I want to acheive the same results as below but I want to get it from the Product
relationship.
ProductPrice::keyBy('id')
推荐答案
您必须创建自己的关系:
You have to create your own relationship:
<?php
namespace App\Helpers\Classes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class HasManyKeyBy extends HasMany
{
private $keyBy;
public function __construct($keyBy, Builder $query, Model $parent, string $foreignKey, string $localKey)
{
$this->keyBy = $keyBy;
parent::__construct($query, $parent, $foreignKey, $localKey);
}
public function getResults()
{
return parent::getResults()->keyBy($this->keyBy);
}
protected function getRelationValue(array $dictionary, $key, $type)
{
return parent::getRelationValue($dictionary, $key, $type)->keyBy($this->keyBy);
}
}
为简单起见,我还建议您创建一个特征:
For the sake of simplicity I also recommend you to create a trait:
<?php
namespace App\Helpers\Traits;
use Illuminate\Database\Eloquent\Relations\HasMany;
trait HasManyKeyBy
{
/**
* @param $keyBy
* @param $related
* @param null $foreignKey
* @param null $localKey
* @return HasMany
*/
protected function hasManyKeyBy($keyBy, $related, $foreignKey = null, $localKey = null)
{
// copied from \Illuminate\Database\Eloquent\Concerns\HasRelationships::hasMany
$instance = $this->newRelatedInstance($related);
$foreignKey = $foreignKey ?: $this->getForeignKey();
$localKey = $localKey ?: $this->getKeyName();
return new \App\Helpers\Classes\HasManyKeyBy($keyBy, $instance->newQuery(),
$this, $instance->getTable().'.'.$foreignKey, $localKey);
}
}
现在,您可以将此特征包括在模型中,并使用$this->hasManyKeyBy
受保护的方法:
Now, you can include this trait into your model, and use $this->hasManyKeyBy
protected method:
[...]
class Product extends Model
{
use HasManyKeyBy;
public function pricing()
{
return $this->hasManyKeyBy('id', ProductPrice::class, 'prod_id', 'id');
}
[...]
}
这篇关于Laravel Eloquent获得与keyBy的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!