我目前正在使用 Laravel、Inertiajs 和 Vuejs 創建一個博客,我需要一些關于獲取用戶名邏輯的幫助。
我有3張桌子:
用戶:
- 身份證 (pk)
- 姓名
博客:
- 身份證 (pk)
- user_id(外鍵)
注釋:
- 身份證 (pk)
- blog_id(外鍵)
- user_id(外鍵)
我有一個博客頁面,它嵌套在來自 web.php 的動態路由中:
Route::get('/blogs/{id}', [BlogController::class, 'show'])->name("blogs.show");
博客頁面包含一篇博客文章和一個評論部分,由 BlogController 呼叫:
public function show(Blog $id)
{
$user = User::find($id->user_id)->name;
return Inertia::render('Components/Blog', [
'blog' => [
'id' => $id->id,
'name' => $user,
'title' => $id->title,
'body' => $id->body,
'created_at' => $id->created_at,
'updated_at' => $id->updated_at,
'comments' => $id->blogComments()->orderByDate()->get()->all(),
],
]);
}
就獲取博主的用戶名而言,它$user = User::find($id->user_id)->name;在 Vue 組件中作為一個blogprop: 運行并從 Vue 組件中回呼<p>{{ blog.name }}</P>。現在,我想要的是在評論部分也呼叫用戶名(參見下面的目標)。

上面的評論部分是從 BlogController 中的 show() 方法呼叫的:
<template>
<div>
<div
v-for="comment in blog.comments"
:key="comment.id"
class="hover:bg-gray-100 focus-within:bg-gray-100"
>
<p>comment id: {{ comment.id }}</p>
<p>comment body: {{ comment.body }}</p>
</div>
</div>
</template>
<script>
export default {
props: {
blog: Object,
},
};
</script>
但我的問題是,我無法完全理解從Usersshow() 方法內的表中獲取用戶名的邏輯。截至目前,通過在控制器呼叫 Comments 表中的外鍵到 Blogs 表中的主鍵,Blogs 表和 Comments 表之間存在一對多關系:'comments' => $id->blogComments()->orderByDate()->get()->all(),
那么如何通過將 Comments 表(在 BlogController 內)中的外鍵呼叫到 Users 表中的主鍵來添加另一個層呢?
我已經在這里呆了幾個小時,我確信我只是遺漏了一些簡單的東西,所以如果有一雙新的眼睛來看待這個,我將不勝感激。
謝謝你。
uj5u.com熱心網友回復:
如果我猜對了,我想您想在評論部分添加評論的作者姓名。
因此,您需要添加評論和用戶之間的關系,如下所示:
class Comment extends Model
{
/**
* Get the author that wrote the book.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
然后將 Inertia 中的注釋更改為如下所示以加載用戶模型:
'comments' => $id->blogComments()->with('users')->orderByDate()->get()->all(),
然后你可以像這樣獲得評論作者:
<div
v-for="comment in blog.comments"
:key="comment.id"
class="hover:bg-gray-100 focus-within:bg-gray-100"
>
<p>comment id: {{ comment.id }}</p>
<p>comment body: {{ comment.body }}</p>
<p>comment author: {{ comment.user.name }} </p>
</div>
請試試這個,讓我知道它是否有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370599.html
下一篇:如何有效地從樹結構構建一棵樹
