【问题标题】:Get grandchildren to model with Laravel eloquent让孙子们用 Laravel eloquent 建模
【发布时间】:2021-03-20 16:56:08
【问题描述】:

我有以下型号 类型->类别->任务

哪里类别可以属于不同的类型。 这里我在 Category Model 中使用了 morphTo

类别模型

class Category extends Model {


public function categorize(){
    return $this->morphTo();
}
public function tasks(){
    return $this->belongsToMany(Task::class,'task_category');
}
public function types(){
    return $this->belongsTo(Type::class);
}
}

在类型中我使用 morphMany

class Type extends Model
{
    //
    protected $fillable = [
        'slug'
    ];
    public function categories(){
        return $this->morphMany(Category::class,'categorize');
    }
    public function project(){
        return $this->belongsTo(Project::class);
    }
   /*  public function tasks(){
        return $this->hasManyThrough(
            Task::class,
            Category::class,

        );
    } */
}

这按预期工作,但我不知道我在任务控制器中如何通过类型模型根据类型和所有类别获取所有任务。我尝试了hasManyThrough,但它不起作用,因为任务和类别是通过数据透视表关联的。

目前我有

$type = Type::with('categories')->where('slug', $type)->first();

这让我得到了带有类别的类型,但如前所述,我想在每个类别对象下获得相关的任务。 如果有什么不清楚的地方,我很乐意澄清和纠正任何需要的东西。非常感谢所有帮助。

【问题讨论】:

    标签: php database laravel


    【解决方案1】:

    Laravel 允许预先加载嵌套关系

    $type = Type::with('categories.tasks')->where('slug', $type)->first();
    

    Laravel 文档:https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

    【讨论】:

    • 哇,你不知道我已经尝试了多少解决这个问题,而我所需要的只是 OO,非常感谢队友,我会在几分钟内标记为 SO 允许我解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多