【问题标题】:How to get todos in relation with a todolist?(solved)如何获取与 todolist 相关的 todos?(已解决)
【发布时间】:2021-10-22 20:37:33
【问题描述】:

应用程序的行为应如下所示: 登录完成后,我拥有了所有的 todolist,因此我必须获取这些 todolist 的所有 todo,而不仅仅是来自特定 todolist 的 todo。

我唯一希望发生的事情是 todos 应该只出现在相对 todolist 上。

AXIOS 请求

getTodos(todolist) {
      axios
        .get(`http://127.0.0.1:8000/api/todolists/${todolist}/todos`)
        .then((res) => {
          this.todos = res.data;
          console.log(res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    },

Vue 模板

    <div
      v-if="todolists.length > 0 && !loading"
      class="todolist-row h-100 py-5"
      :class="todolists.length == 1 ? 'todolist-1' : ''"
    >
      <div class="todolist" v-for="todolist in todolists" :key="todolist.id">
        <div class="td-title">
          <h5 class="text-center m-0 py-2 text-light">
            {{ todolist.title }}
          </h5>
        </div>
        <div class="td-inputs d-flex align-items-center justify-content-center">
          <input class="px-2" type="text" />
          <button type="submit">
            <i class="fas fa-plus fa-2x"></i>
          </button>
        </div>
        <div class="px-2">
          <div v-for="todo in todos" :key="todo.id">
            {{ todo.title }}
          </div>

          <div><i class="fas fa-times" @click="cancel(todolist.id)"></i></div>
        </div>
      </div>
    </div>

路线

Route::get('todolists/{todolist}/todos', 'TodoController@index');

控制器

public function index(Todolist $todolist) {
        return $todolist->todos;
    }

我已经尝试过这个计算属性(然后在 v-for 中传递它)但它不起作用

computed: {
    filtered() {
      this.todolists.forEach( todolist => {
        this.todos.filter( todo => todo.todolist_id == todolist.id)
        return this.todos
      })
    }
  },

------------------问题解决了---------------- ----------------

在 TodolistController 中,我刚刚添加了“->with('todos')”,它在 todolist 对象数组中返回了一个 todos 对象数组。

然后在“todolist.todos”上使用 v-for,我得到了我需要的 todo。

我什至不需要 api。

TodolistController

$userTodolist = Todolist::where('user_id', Auth::id())->orderBy('id', 'DESC')->with('todos')->get();

VUE 模板

<div v-for="todo in todolist.todos" :key="todo.id">
     {{ todo.title }}
</div>

【问题讨论】:

  • 你能用你的路线文件更新你的问题吗?
  • 执行dd($todo-&gt;todolist) 并检查为什么它返回null 而不是模型。可能与您数据库中的数据有关。另外,邮政编码不是图片。使复制/粘贴变得困难。
  • 已更新。但是数据库似乎还可以,我需要的所有关系都在它们需要的地方。

标签: laravel vue.js axios


【解决方案1】:

您没有此路由的路由参数。您的方法签名Todo $todo 将导致发生依赖注入,而不是路由模型绑定;所以$todo 是一个注入的新的不存在的 Todo 模型实例。

如果您希望它成为路由模型绑定,您需要有一个名为 todo 的路由参数。我会以不同的方式设置路线,并使其更像是一个嵌套资源的想法:

Route::get('todolists/{list}/todos', ...);

public function index(Todolist $list)
{
    return $list->todos;
}

假设 Todolist 上的关系命名为todos 以获取其所有待办事项。

【讨论】:

  • 当然,我为什么没想到呢?显然我需要在引用 todolist 的路由中添加一个参数,谢谢!!!
  • 不幸的是它没有解决问题。我改变了路线,然后在Vue中我调用了created中的函数,但我无法传入todolist.id
猜你喜欢
  • 2016-05-16
  • 2017-01-18
  • 1970-01-01
  • 2021-10-04
  • 2012-07-31
  • 1970-01-01
  • 2016-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多