尝试在laravel中获取非对象错误的属性

时间:2017-05-04 09:36:45

标签: php mysql laravel laravel-5

我一直在尝试将我的用户的User_id与Creator_id匹配,以在我的帖子中显示创建者用户名 但我正试图从非对象错误获取属性,我不能得到它周围

我控制器中的功能 postcontroller.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;
    }

2 个答案:

答案 0 :(得分:2)

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

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

但是对于您的问题,您应该尝试在Post Model中添加它

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

答案 1 :(得分:0)

您的users表是否有像user_id这样的列?

我认为您已使用帖子creator_id检查了用户表ID。