【发布时间】: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