如果我创建了一篇博文,我怎么能将我的名字与之相关联?例如,在列出所有博客帖子的页面上,我将看到他们创建的帖子的用户名。是
在我的帖子控制器中:
public function __construct(Post $post, User $user)
{
$this->middleware('auth',['except'=>['index','show',]]);
$this->post = $post;
$this->user = $user;
}
public function show($id)
{
$user = $this->user->first(); // This seems to show the first user
$post = $this->post->where('id', $id)->first(); // Grabs the assigned post
}
在我的show.blade.php
:
{{ $user->name }}
如何显示创建帖子的用户的姓名?我认为$user = $this->user->first();
会起作用。我是Laravel的新手,我正在使用Laravel 5.
谢谢!
修改 用户模型:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, BillableContract {
use Authenticatable, CanResetPassword;
use Billable;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password', 'company_url', 'tagline','company_name', 'company_description'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* @var array
*
*/
protected $dates = ['trial_ends_at', 'subscription_ends_at'];
public function posts()
{
return $this->hasMany('App\Post')->latest()->where('content_removed', 0);
}
}
发布模型:
class Post extends Model {
/**
* Fillable fields for a new Job.
* @var array
*/
protected $fillable = [
'post_title',
'post_description',
'post_role',
'post_types',
'post_city',
'post_country',
'template',
'content_removed',
];
public function users()
{
return $this->hasMany('App\User')->orderBy('created_at', 'DESC');
}
public function creator()
{
return $this->belongsTo('App\User');
}
}
答案 0 :(得分:1)
第一 您需要将以下行添加到帖子模型
public function creator()
{
return $this->belongsTo('App\User','user_id', 'ID');
}
然后在你显示方法
public function show($id)
{
$post = $this->post->with('creator')->findOrFail($id);
return view('show',compact('post'));
}
在你的show.blade.php
{{ $post->creator->name }}