2014-11-24 106 views
0

我在2天前开始学习。我做了一个简单的用户登录和博客发布系统。无法获得Laravel关系,新手

这里是我的代码,将获取所有博客文章,也应该加入表一起

这是正确的?综观文档和搜索,这似乎是正确的,但我不断收到以下错误:

未定义的属性:照亮\数据库\雄辩\收藏:: $用户

我的博客表structed这样: enter image description here

而且用户表像这样 enter image description here

博客型号

class Blog extends Eloquent { 

    public function user() 
    { 
     return $this->belongsTo('User', 'user_id', 'id'); 
    } 
} 

用户模型

class User extends Eloquent implements UserInterface, RemindableInterface { 

    use UserTrait, RemindableTrait; 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'users'; 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = array('password', 'remember_token'); 


    public function blog() 
    { 
     return $this->hasMany('Blog', 'id', 'user_id'); 
    } 
} 

回答

1

在你index()功能试试这个

public function index() 
{ 
    $posts = Blog::all(); 

    return View::make('blogs.index', array('posts' => $posts)); 
} 

然后在blogs.index你可以在你的DB(刀片)

{{ $posts->user->id }}{{ $posts->user->email }}或任何列访问关系

+0

你能否解释它是如何知道总是进行连接的?这一点令我困惑 – Ben 2014-11-24 20:59:59

+0

我希望我知道背后的深层技术原因,但我会尽我所能! Laravel在它的模型中使用了雄辩。雄辩会自动加载你为你定义的关系,然后你就可以使用称为“动态属性”的东西来访问这些关系。基本上它真的很聪明! – 2014-11-24 21:09:12

0

随着$blog = new Blog;你开始创建一个新的博客条目。您真正需要做的是查询博客表并获取用户,这可以通过预先加载轻松完成。试试这个...

$blogs = Blog::with('users');

然后,当你创建你的观点,你要使用的东西送的博客在您看来是这样的...的with()方法的第一个参数是你想要的名称给你的视图中的变量,第二个是发送的实际变量。

return View::make('blogs.index')->with('blogs', $blogs);