2014-08-27 47 views
0

我正在嘗試與我的用戶表和我的news_posts表進行關係。當我查看運行的查詢時,會顯示跟進情況。新聞發佈和用戶關係與Laravel雄辯ORM

select * from `news_posts` where `news_posts`.`deleted_at` is null and `id` = '1' limit 1 
select * from `users` where `users`.`deleted_at` is null and `users`.`id` is null limit 1 

所以我想弄明白爲什麼它說user.id爲NULL。

我試圖訪問$ news_post-> author-> first_name和$ news_post-> author-> first_name。

My Laravel Pastebin

<?php 

class User extends Eloquent implements UserInterface, RemindableInterface { 

    public function post() 
    { 
     return $this->hasMany('NewsPost', 'user_id'); 
    } 
} 

class NewsPost extends \Eloquent { 

    use SoftDeletingTrait; 

    protected $table = 'news_posts'; 

    protected $fillable = []; 

    protected $dates = ['deleted_at']; 

    // DEFINE RELATIONSHIPS -------------------------------------------------- 
    public function category() 
    { 
     return $this->belongsTo('NewsCategory'); 
    } 

    public function author() 
    { 
     return $this->belongsTo('User'); 
    } 
} 


table: news_posts 
fields: id, user_id, title, content 

table: users 
fields: id, username, first_name, last_name 
+0

哪來的,你必須運行這些查詢的代碼? – 2014-08-28 16:47:58

回答

2

試試這個

foreach (NewsPost::all() as $news_post) 
{ 
    echo $news_post->author->name; 
}