2014-08-27 65 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; 
}