[英]Laravel Eloquent get relationship with keyBy
我有一个具有hasMany
关系的Product
模型
public function pricing()
{
return $this->hasMany('App\ProductPrice', 'prod_id', 'id');
}
然后我得到了关系
Product::with('pricing')->all();
如何检索以id
为键的pricing
关系。 我知道我可以使用keyBy('id)
在Collection
上执行此操作,但它不适用于查询。
我想获得与下面相同的结果,但我想从Product
关系中获得它。
ProductPrice::keyBy('id')
一个快速的解决方法是使用 setRelation 方法替换数组中的当前关系。 在你的情况下:
$product = Product::with('pricing')->all();
$product->setRelation('pricing', $product->pricing->keyBy('id'));
您必须创建自己的关系:
<?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);
}
}
为了简单起见,我还建议您创建一个特征:
<?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
保护方法:
[...]
class Product extends Model
{
use HasManyKeyBy;
public function pricing()
{
return $this->hasManyKeyBy('id', ProductPrice::class, 'prod_id', 'id');
}
[...]
}
您还可以做的是定义一个访问器:
/**
* @return Collection
*/
public function getPricingByIdAttribute() : Collection
{
return $this->pricing->keyBy('id');
}
然后在集合中返回的每个产品上,您可以使用以下 id 获取定价:
$pricing = $product->pricing_by_id;
如有必要,请确保仍然急切加载定价:
$products = Product::query()->with('pricing')->get();
此外,当使用 json 在例如 API 中返回产品时,您可以使用附加到 json :
$products->each->append('pricing_by_id');
问题是你不能'keyBy'一个现有的关系。
但是,您可以创建一个返回的“假”属性,该属性可以被键入。 所以与其:
$products = Product::with('pricing') -> all();
$products -> keyedPricing = $products -> pricing -> keyBy('id');
$products -> addVisible('keyedPricing');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.