【问题标题】:Get specific data from another table using foreign key in Laravel Livewire在 Laravel Livewire 中使用外键从另一个表中获取特定数据
【发布时间】:2021-08-18 09:13:15
【问题描述】:

我是一个新的 Livewire 用户,我想使用我的 Blog 表中用户的外键从 User 表中获取特定名称。我不确定如何将代码放入render() 和 Blade 模板中。我见过这样的事情:{{ blogs->id->name }}。我怎样才能想出一个解决方案?

用户表

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

博客表

Schema::create('blogs', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained();
    $table->string('title');
    $table->text('heading')->nullable();
    $table->text('paragraph');
    $table->text('featured_img');
    $table->timestamps();
});

在用户模型中声明

public function blogs() 
{
    return $this->hasMany(Blogs::class);
}

在博客模型中声明

public function user() 
{
    return $this->belongsTo(User::class);
}

Blogs 类中的render() 方法

public function render()
{
    $blogs = Blogs::where('user_id', Auth::id())->orderBy('created_at', 'desc')->paginate(3);
    $user = User::where('id', Auth::id())->get();

    return view('livewire.admin.blogs', [
        'blogs' => $blogs,
        'user' => $user
    ])->layout('layouts.admin');
}

【问题讨论】:

    标签: laravel eloquent laravel-livewire


    【解决方案1】:

    您似乎已经认识该用户并希望返回该特定用户的所有博客文章?如果是这种情况,您可以对已定义的关系执行以下操作。我还假设您想要登录用户的博客文章。

    public function render()
    {
        return view('livewire.admin.blogs', [
            // No need to add the posts here, get them from the user model
            'user' => auth()->user(),
        ])->layout('layouts.admin');
    }
    

    然后在你的刀片中为用户循环浏览博客文章:

    <p>The blog posts for {{ $user->name }}</p>
    @foreach ($user->blogs()->paginate(3) as $post)
    <h1>{{ $post->title }}</h1>
    <p>{{ $post->heading }}</p>
    @endforeach
    

    更新以获取用户

    如果您想获取特定博客文章的用户,则可以在博客模型本身上使用用户关系。

    // From the Blog model access the User relationship and return 
    // the `name` for the specific user who created the blog post.
    $post->user->name
    

    【讨论】:

    • 感谢@Leon 先生的快速回答。但我想返回创建博客的用户的姓名。因此,在我的博客架构中,用户具有外键 ID“user_id”,但我不知道如何在用户架构中获取 user_id 的名称。
    • @nhaj0415 我更新了我的答案,让您从博客模型访问用户。
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多