2016-10-06 39 views
0

當我在我的routes/web.php文件中使用以下代碼時,每次訪問/ user/{id}/post url時,都會收到錯誤'試圖獲取非對象的屬性'。如何從Laravel的默認用戶類讀取數據庫數據?

路線/ 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

如果用戶與帖子有一個關聯,最好將關係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); 
}