【问题标题】:Laravel polymorphic relation load model by morph name and foreign keyLaravel 多态关系通过 morph 名称和外键加载模型
【发布时间】:2019-08-15 19:12:02
【问题描述】:

我正在尝试使用 morphname 键为可评论模型(通过使用多态关系创建)创建评论。

例如;我想创建一个评论,给出变形名称(博客)和foreign_key(1)。但变形名称可能会改变。所以我们不知道请求可以使用哪个键。我不想为每个资源创建操作。

AppServiceProvider:

Relation::morphMap([
    'blog' => \App\Models\Blog\BlogPost::class,
    'product' => \App\Models\Commerce\Product::class,
]);

控制器 -> 动作:

$this->validate($request, [
    'commentable_model' => 'required|string',
    'commentable_id' => 'required|integer|min:1',
    'comment' => 'required|string'
]);

// i am trying to load data using morph name and foreign key here; but it's not working.
$model = $request->commentable_model::findOrFail($request->commentable_id);

$comment = new Comment;
$comment->comment = $request->comment;
$comment->commentable()->associate($model);
$comment->user()->associate(auth('api')->user());
$comment->save();

可评论关系:

Schema::create('comments', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->text('comment');
    $table->integer('parent_id')->unsigned()->nullable();
    $table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade');
    $table->morphs('commentable');
    $table->timestamps();
});

数据:

commentable_model => '博客', commentable_id => 1

我将通过 api 端点发送这些数据。所以,我只想使用 morhpnames,而不是完整的类名。

我无法让它工作。

有什么想法吗?

【问题讨论】:

  • 怎么不工作了?请添加commentable 关系。
  • @JonasStaudenmeir 已更新。
  • 究竟是什么不工作?最后dd($comment->getAttributes())的结果是什么?
  • 其实我上面提到过:$model = $request->commentable_model::findOrFail($request->commentable_id);这一行。这个想法是;在给定的“博客”(或任何变形名称)模型上使用 findOrFail 方法。

标签: laravel eloquent polymorphism


【解决方案1】:

我找到了解决方案,实际上它一直在我的眼前......

我们正在使用 Relation 类进行映射。

我检查了我们是否可以使用任何方法或变量访问关系,答案是肯定的。

简短的回答是;

Relation::$morphMap

将所有映射作为数组返回。

我对这个问题的解决方案是;

$model = Relation::$morphMap[$request->commentable_model]::findOrFail($request->commentable_id);

使用我们给定的变形名称(即博客)访问该数组值。

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 2021-05-23
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多