【发布时间】:2016-08-04 07:50:57
【问题描述】:
我有一个关于 Laravel 的关系模型的问题
comment table id post_id
post table id author_id
author table id name
我想使用关系模型通过post表在评论模型中获取作者姓名,如何实现。非常感谢。
【问题讨论】:
标签: laravel model relationships
我有一个关于 Laravel 的关系模型的问题
comment table id post_id
post table id author_id
author table id name
我想使用关系模型通过post表在评论模型中获取作者姓名,如何实现。非常感谢。
【问题讨论】:
标签: laravel model relationships
您必须在帖子和用户之间创建 hasMany 关系。为此,您必须在模型中编写此关系函数:
后模型:
// A post can have 1 author
public function author() {
return $this->belongsTo('App\User');
}
用户模型:
// A user can have multiple posts
public function posts() {
return $this->hasMany('App\Post');
}
【讨论】:
Laravel 中的关系非常容易实现,并且由于 API 的表达性而非常容易理解。所以在你的情况下,逻辑是这样的:
评论属于帖子,帖子属于作者
所以考虑到您有 Comment、Post 和 Author 模型,每个模型都应该定义一个反映上述逻辑的关系方法。
Comment 模型如下所示:
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
Post 模型看起来像这样:
class Post extends Model
{
public function author()
{
return $this->belongsTo(Author::class);
}
}
然后您可以通过这些关系轻松访问帖子作者姓名:
Comment::find(1)->post->author->name;
从上面的代码中可以看出,为关系编写代码非常容易,因为方法名称确实具有暗示性。您可以在Laravel Documentation 中阅读有关 Eloquent 关系的更多信息。
【讨论】:
class Post extends Model
{
public function author()
{
return $this->belongsTo(Author\class)->select('name');
}
}
Comment::with('author')->find(1);
in blade
{{$comment->auther['name']}}
【讨论】:
这是我使用 Laravel 8 和 belongsTo 的答案。
在我的解决方案中,我首先创建了用户和帖子的关系
// Post migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title',160)->unique();
$table->string('image');
$table->text('content')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
在 My Post 模型中,我创建了 authors 函数
// Post Model
public function authors()
{
return $this->belongsTo(User::class, 'user_id','id');
}
'user_id' 是 foreignKey,id 是 ownerKey
现在我使用这个在我的控制器中调用 Post 模型
//Post Controller
//return latest posts with the author and paginate it
public function index()
{
$posts = Post::latest()->with('authors')->paginate(3);
return view('blog',compact('posts'));
}
最后,我在 blog.blade 文件中使用它
//blog.blade
<hr>
@foreach ($posts as $post)
<h3>{{$post->title}}</h3><pre>{{$post->role}}</pre>
//get author name forech post
<pre>{{$post->authors['name']}}</pre>
@endforeach
<hr>
【讨论】: