【问题标题】:Binding several inherited models to the same route laravel将几个继承的模型绑定到同一个路由 laravel
【发布时间】:2019-01-18 15:59:13
【问题描述】:

我有 3 个模型,它们都继承了抽象的 Plan 模型、BehaviourPlanAffirmationPlanProfilePlan

是否可以让所有这些都通过同一条路线提供服务?这是我到目前为止所得到的,但是因为Plan 是抽象的,所以它会抛出Target [App\Plan] is not instantiable.

Route::prefix('plans')->group(function () {
    Route::get('/{plan}', function (\App\Plan $plan) {
        dd($plan);
    });
});

【问题讨论】:

  • 我怀疑你要么必须使 Plan 非抽象,要么使用 Model 作为类型提示。
  • 您可以将路由指向一个控制器,然后实例化这三个模型并在该控制器中使用它们
  • @AmritShrestha 我认为您误读了这个问题。 OP 想要 plan 路由采用 几个 可能的类之一,每个类都继承自父 App\Plan。有点像多态关系。

标签: php laravel routes


【解决方案1】:

我已经解决了这个问题,方法是将每个计划的 slug 更改为以它们的类型为前缀,然后运行 ​​if 语句来检索控制器中的计划,例如:

public function show(Student $student, string $plan_id)
    {
        $plan = null;
        if(starts_with($plan_id, "behaviour"))
        {
            $plan = BehaviourPlan::where('slug', $plan_id)->first();
        }
        else if(starts_with($plan_id, "affirmation"))
        {
            $plan = AffirmationPlan::where('slug', $plan_id)->first();
        }
        else if(starts_with($plan_id, "profile"))
        {
            $plan = ProfilePlan::where('slug', $plan_id)->first();
        }

        if ($plan == null)
            return abort('404');

        dd($plan);
    }

虽然看起来有点粗略,所以我仍在寻找一种更简洁的方法来解决这个问题

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 2015-08-28
    • 2016-06-04
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多