如何从Laravel中的默认User类读取数据库数据?

时间:2016-10-06 06:37:10

标签: laravel class model

当我在routes / web.php文件中使用以下代码时,我不断收到“尝试获取非对象属性”的错误。每次我访问/ user / {id} / post url。

路由/ web.php

use App\Post;
use App\User;

Route::get('/user/{id}/post', function($id) {
  return User::find($id)->name;
});

应用/ user.php的

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts() {
        return $this->hasOne('Post');
    }
}

应用/ post.php中

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    // protected $table = 'posts';

  use SoftDeletes;

  protected $dates = ['deleted_at'];
  protected $fillable = [''];
}

如何查看表用户中存储的数据?我在那里放了一些虚拟数据来尝试检索它。

1 个答案:

答案 0 :(得分:1)

如果用户与Post有一个关系,最好建立关系post()而不是posts()并发布belongsTo用户。

用户模型:

public function post() {
    return $this->hasOne('App\Post');
}

发布模型:

 public function user()
    {
        return $this->belongsTo('App\User'); 
    }

然后,这会给所有用户的帖子和用户名。

$users=User::with('post')->get();
foreach($users as $user)
{
  print_r($user->name);
  print_r($user->post);
}