laravel - Laravel Eloquent获得与keyBy的关系

标签 laravel eloquent

我有一个Product关系的hasMany模型

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

然后我得到了关系
Product::with('pricing')->all();

如何以pricing为键来检索id关系。我知道我可以使用CollectionkeyBy('id)上执行此操作,但不适用于查询。

我想获得与以下相同的结果,但我想从Product关系中获得它。
ProductPrice::keyBy('id')

最佳答案

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

$product = Product::with('pricing')->all();
$product->setRelation('pricing', $product->pricing->keyBy('id'));

关于laravel - Laravel Eloquent获得与keyBy的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31147107/

相关文章:

php - 如何将 Laravel Eloquent 查询的一部分传递给方法

javascript - 模块构建失败 : Error: write EPIPE (or make processCssUrls:false) in css imports Laravel Mix

拉拉维尔 4 : Order by in a pivot table

laravel - 重写 eloquent create() 方法

php - 在 laravel 中调用未定义的方法 Illuminate\Database\Eloquent\Collection::whereHas()

laravel - 检查 Blade 中 Stack 指令的内容

php - Laravel 关系,与祖 parent 相同的 parent : good practice or not?

mysql - 在 Laravel5.4 中将数据插入数据透视表

php - 拉拉维尔 5 : Trying to get property of non-object error with relationships

php - 如何在 Laravel 5.2 框架中创建 sqlite 文件?