【问题标题】:Get Model and id of the Model you are adding a note to获取要添加注释的模型的模型和 ID
【发布时间】:2017-10-18 02:22:57
【问题描述】:

基本上,

我有一个与视频和用户有多态关系的笔记表,我想确定如何在我的 NotesController 中的 store 方法上获得我要添加笔记的模型,以及该表中的 id。这是我对我的商店方法的创建查询

       $note = Note::query()->create([
            'body' => $request->get('body'),
            'user_id' => \Auth::id(),
            'noteable_id' => 1, **(needs to be dynamic)**
            'noteable_type' => Video::class, **(needs to be dynamic)**
        ]);

刀片

                    <form action="{{route('admin.note.store'}}" method="post">
                        {{csrf_field()}}
                        <div class="input-group">
                            <input id="btn-input" name="body" required="true" type="text" class="form-control input-sm" placeholder="Type your message here...">
                            <span class="input-group-btn">
                                <button type="submit" class="btn btn-warning btn-sm" id="btn-chat">
                                    Submit
                                </button>
                            </span>
                        </div>
                    </form>

基本上我想知道如何检索 noteable_type =(我正在更新的模型)和 noteable_id(我要添加注释的记录的 ID)

有什么方法可以根据请求动态检索它吗?

谢谢

【问题讨论】:

  • 你能发布你的刀片模板吗?
  • 添加到原帖

标签: laravel model-view-controller model polymorphism


【解决方案1】:

您需要以某种方式获取视频或任何其他模型。如果您的路线包含视频 ID,那么您可以在控制器中使用它。这里有一些方法可以做到这一点。

//Get your video model
$video = Video::find(...);

$note = \Auth::user()->create([
    'body' => $request->get('body'),
    'noteable_id' => $video->id,
    'noteable_type' => get_class($video),
]);

// OR

$note = new Note([
    'body' => $request->get('body'),
    'user_id' => \Auth::id(),
]);

$video->note()->save($note);

运行php artisan route:list 并发布它,以便我可以建议您如何获取模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2015-04-26
    • 2016-09-30
    相关资源
    最近更新 更多