Laravel Eloquent 获取与 keyBy 的关系

Was*_*sim 6 laravel eloquent

我有一个ProducthasMany关系的模型

public function pricing()
    {
        return $this->hasMany('App\ProductPrice', 'prod_id', 'id');
    }
Run Code Online (Sandbox Code Playgroud)

然后我得到了关系

Product::with('pricing')->all();
Run Code Online (Sandbox Code Playgroud)

如何检索pricingid作为键的关系。我知道我可以在Collectionwith上做到这一点,keyBy('id)但它不适用于查询。

我想获得与下面相同的结果,但我想从Product关系中得到它。

ProductPrice::keyBy('id')
Run Code Online (Sandbox Code Playgroud)

vba*_*osh 7

你必须创建自己的关系:

<?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);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了简单起见,我还建议您创建一个特征:

<?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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以将此特征包含到您的模型中,并使用$this->hasManyKeyBy受保护的方法:

[...]
class Product extends Model
{
    use HasManyKeyBy;

    public function pricing()
    {
        return $this->hasManyKeyBy('id', ProductPrice::class, 'prod_id', 'id');
    }

    [...]
}
Run Code Online (Sandbox Code Playgroud)


小智 5

一个快速的解决方法是使用 setRelation 方法替换数组中的当前关系。在你的情况下:

$product = Product::with('pricing')->all();
$product->setRelation('pricing', $product->pricing->keyBy('id'));
Run Code Online (Sandbox Code Playgroud)


Mat*_*ald 0

问题是你不能“keyBy”现有的关系。

但是,您可以创建一个返回的“假”属性,该属性可以设置键控。所以与其:

$products = Product::with('pricing') -> all();
$products -> keyedPricing = $products -> pricing -> keyBy('id');
$products -> addVisible('keyedPricing');
Run Code Online (Sandbox Code Playgroud)