我试图从用户表中获取帖子的作者,两个表都被创建并且两者都有关系。我在我的控制器中有这个代码
public function viewPost($id)
{
$mytime = Carbon\Carbon::now();
$post = Post::find($id);
$by = $post->user()->get();
$user = Auth::user();
$this->layout->content = View::make('interface.viewPost')
->with('posts', $post )
->with('users',$user)
->with('date',$mytime)
->with('by',$by);
}
这是用户/帖子的模型
帖子模型: class Post扩展了Eloquent {
protected $fillable = array('email', 'password','title','content');
protected $table = 'posts';
public function user()
{
return $this->belongsTo('User');
}
}
和我的用户模型
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
protected $fillable = array('email','password','title','content');
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function post()
{
return $this->hasMany('Post','user_id');
}
public function comments()
{
return $this->hasMany('Comment');
}
}
答案 0 :(得分:0)
您必须指定要加载您获得的帖子的用户。尝试以下
public function viewPost($id)
{
$mytime = Carbon\Carbon::now();
$post = Post::with('user')->find($id);
$by = $post->user;
...
}
您甚至无需向视图发送$by
,因为您可以从视图内部$post->user->username