繁体   English   中英

急切加载模型使用 with 但给它另一个名字 - Laravel 5.2

[英]Eager load model using with but giving it another name - Laravel 5.2

是否可以使用 with 方法使用预先加载但给它另一个名称? 类似的东西:

->with('documents as product', 'documents.documents as categories')

我有一个可以是产品或类别的文档表,急切加载正在工作,但仅通过文档名称而不是实际名称来检索文档并不那么友好。

目前任何 Laravel 版本都不支持此功能。 你最好的办法是复制你的关系并根据你的需要命名它们。 例如:

class Post extends Model
    public function documents() {
        return $this->hasMany(Document::class);
    }

    public function products() {
        return $this->hasMany(Document::class)
            ->where('type', 'product'); // Scope the query, if necessary
    }

    public function categories() {
        return $this->hasMany(Document::class)
            ->where('type', 'category'); // Would a Document really be of type 'category', though? Looks like a code smell.
    }
}

$postsWithAllDocs = Post::with('documents')->get();
$postsWithProductsOnly = Post::with('products')->get(); // Only eager load Documents of type 'product'

在旁注中,您提到Document可以是产品或类别,这在逻辑上似乎没有多大意义。 部分问题可能可以通过重新考虑数据库和关系的结构来解决。

急切加载告诉“也加载此关系数据”,因此接下来您无需进一步查询即可访问主题->关系

如果你想重命名关系,也许你应该重命名模型中的关系,而不是在预先加载中

你也可以通过添加虚拟属性来绕过这个:

function getProductAttribute(){
    return $this->document;
}

在原始文档上留下急切加载

导致产品属性与文档相同:

$subject->product === $subject->document

我问了自己同样的问题,由于我没有在网上找到令人满意的答案,所以我做了以下工作。 我有:

$o->load('X');

但我希望$o对象具有属性YX关系的值。 由于我已经$o定义Y关系,因此我无法将X重命名为Y并完成工作。 所以我做了

$o['Y'] = $o->X();

我知道这不是最好的解决方案,但它适用于我的情况:)

注意: loadwith产生完全相同数量的 sql 查询- 您需要选择更适合您情况的查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM