【问题标题】:How do I read database data from default User class in Laravel?如何从 Laravel 的默认用户类中读取数据库数据?
【发布时间】:2016-10-06 15:54:48
【问题描述】:

当我在 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;
});

应用程序/用户.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');
    }
}

App/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 = [''];
}

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

【问题讨论】:

    标签: laravel class model


    【解决方案1】:

    如果用户与帖子有一个关系,最好建立关系post()而不是posts()和帖子属于用户。

    用户模型:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      相关资源
      最近更新 更多