【问题标题】:How do I get the user-name in every thread (Laravel)?如何在每个线程(Laravel)中获取用户名?
【发布时间】:2016-06-22 04:45:52
【问题描述】:

我不想让创建的用户的名字是自己的线程。就像迈克尔做了一个关于食物的话题。所以在食物线的底部应该是迈克尔的名字。

我已经为此编写了代码,但它并没有真正起作用。也许你们中的某个人可以找到错误。

我有两个模型。一个线程模型和一个用户模型。

线程模型:

<?php
namespace App\Models\Thread;

use Illuminate\Database\Eloquent\Model;
use App\User;

class Thread extends Model {
    public $table = 'thread';
    public $fillable = [
        'thread',
        'content',
        'user_id'
    ];

    public function userthread() {
        return $this->belongsTo('User','user_id', 'id');

用户模型:

<?php

namespace App;

   use ...

    protected $table = 'users';

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    public function threaduser() {
        return $this->hasMany('App\Models\Thread\Thread','user_id', 'id');
    }
}

现在是控制器方法,我正在尝试获取名称:

 public function show($id)
    {
        $thread = Thread::query()->findOrFail($id);
        $threaduser = Thread::where('user_id', Auth::user()->id)->with('userthread')->get();
        return view('test.show', [
            'thread' => $thread,
            'threaduser' => $threaduser
        ]);
    }

在我的 html 中:

{{$threaduser->name}}

我得到的错误信息是:

未定义属性:Illuminate\Database\Eloquent\Collection::$name(查看:/var/www/laravel/logs/resources/views/test/show.blade.php)

我希望有人可以帮助我。

【问题讨论】:

    标签: php multithreading laravel


    【解决方案1】:

    get() 给你一个集合而不是一个模型,你要么必须对它做一个 foreach 就像

    @foreach ($threadusers as $threaduser)
        {{ $threaduser->userthread->name }}
    @endforeach
    

    如果每个用户只有一个线程,则使用first 而不是get

    当然,取决于你想做什么。

    【讨论】:

    • 我这样做了,但现在它只给了我我数据库中线程下的每个用户:/
    • 你到底做了什么?
    • 我使用了你给我的 foreach 循环。现在我只是让线程中的每个用户都写了
    • 但是你想要什么。你希望你的回应如何
    • 所以你告诉我$threadusers 是用户的集合还是我错过了什么?
    【解决方案2】:

    改成

    {{$threaduser->userthread->name}}
    

    将线程类中的 userthread() 函数更改为

    public function userthread() {
        return $this->belongsTo('App\User','user_id', 'id');
    }
    

    【讨论】:

    • 我做了,但现在我收到此错误消息:找不到类“用户”
    • 我做到了,但现在我得到了和以前一样的错误: Undefined property: Illuminate\Database\Eloquent\Collection::$userthread (in my html)
    • 如果你使用 get(),你需要遍历你的集合。所以构建 foreach 循环来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    相关资源
    最近更新 更多