我有一个具有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')
发布于 2020-04-19 01:12:30
一种快速的解决方法是使用setRelation方法替换数组中的当前关系。在您的案例中:
$product = Product::with('pricing')->all();
$product->setRelation('pricing', $product->pricing->keyBy('id'));
发布于 2019-07-31 17:58:31
你必须创建你自己的关系:
<?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');
}
[...]
}
发布于 2020-08-26 22:02:01
您还可以定义一个accessor
/**
* @return Collection
*/
public function getPricingByIdAttribute() : Collection
{
return $this->pricing->keyBy('id');
}
然后,在Collection中返回的每个产品上,您可以使用以下命令通过id获得定价:
$pricing = $product->pricing_by_id;
如有必要,请确保仍要立即加载定价:
$products = Product::query()->with('pricing')->get();
此外,当使用json返回API中的产品时,您可以使用appending to json。
$products->each->append('pricing_by_id');
https://stackoverflow.com/questions/31147107
复制相似问题