php - 使用 with 但给它另一个名字的预加载模型 - Laravel 5.2

标签 php laravel 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 可以是产品或类别,这在逻辑上似乎没有多大意义。部分问题可能可以通过重新考虑数据库和关系的结构来解决。

关于php - 使用 with 但给它另一个名字的预加载模型 - Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37985900/

相关文章:

laravel - Laravel Eloquent 地如何在appends数组中按访问器排序收集

javascript - vuetify 表页面不工作并重置回 1

php - 使用参数创建 [Laravel 5.2]

php - 带有值(value)引号的 Laravel Multi Insert 问题

php - Mime 类型 PDF php 上传

php - MySQL:时间轴脚本,添加用户帖子和我自己的帖子

laravel - 为什么当我更改命名空间时我的应用程序会崩溃?

与缺少扩展相关的 PHP 错误/异常处理

php - 密码保护链接列表*和*密码保护文件访问

php - 需要替代解决方案,而不是从触发器调用 PHP 代码