我一直在尝试将用户的用户名与创建者的id匹配,以便在我的帖子中显示创建者的用户名
但是我试图从非对象错误中获取属性,我不能自大
我的控制器的功能
后控制器.php:

public function index()
    {
    $allusers = users::getusers();

    $posts = DB::table('posts')->get();
    foreach ($posts as $posts) {
        foreach ($allusers as $allusers) {
            if ($posts->creator_id == $allusers->user_id) {
              array_push($posts,$allusers->username);
            }
        }
    }
     return view('blog',['posts'=>$posts]);
    }

我的模型中的函数:
public static function getusers(){
    $allusers = users::all();
    return $allusers;
    }

最佳答案

在foreach循环中使用相同的变量名:

foreach ($posts as $post) {
    foreach ($allusers as $user) {
        if ($post->creator_id == $user->user_id) {
          array_push($post,$user->username);
        }
    }
}

但是对于您的问题,您应该尝试在Post模型中添加这个
public function user(){
    return $this->belongsTo(User::class, 'creator_id', 'user_id);
}

那么在你看来:
@foreach($posts as $post)
    {{ $post->user->name }}
@endforeach

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse

关于php - 试图在Laravel中获得非对象错误的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43779186/

10-10 15:50