如何在查询中使用 with
从 Blogs 表中获取数据以及博客类别和博客标签。
下面是我的模型和 Controller 代码,我得到的是 Get Blogs Api Error
而不是博客数据。
博客 Controller
public function getBlogs()
{
try {
$blogs = Blog::where('status', 1)
->with('category')
->with('tag')
->with('user')
->with('comment')
->orderBy('id', 'desc')
->paginate(5);
return response()->json($blogs);
} catch (\Illuminate\Database\QueryException $e) {
$e = "Get Blogs Api Error";
return response()->json($e);
}
}
博客模型
class Blog extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->hasMany(Category::class);
}
public function tag()
{
return $this->hasMany(Tag::class);
}
public function comment()
{
return $this->hasMany(Comment::class);
}
}
用户模型
public function blog_user()
{
return $this->hasMany(Blog::class);
}
博客类别模型
public function blog_category()
{
return $this->belongsTo(Blog::class);
}
博客标签模型
public function blog_tag()
{
return $this->belongsTo(Blog::class);
}
博客评论模型
public function blog_comment()
{
return $this->belongsTo(Blog::class);
}
数据库表结构
blogs表结构
blog_categories 表结构
blog_tags表结构
最佳答案
首先把名字改成复数。不是单一的。因为您正在使用一对多。并使用 belongsToMany() 方法。不是 hasMany()。
public function categories(){
return $this->belongsToMany(Category::class);
}
并将数据透视表的名称更改为 blog_category 而不是 blog_categories。它会起作用。您的 BlogCategory 模型将如下所示。
class BlogCategory extends Model {
protected $table = 'blog_category';
public function blog() {
return $this->belongsTo( Blog::class );
}
}
现在您可以获得这样的博客。
$blogs = Blog::with( 'categories' )->get();
这就是您获取任何类别博客的方式。
$category = BlogCategory::where( 'category_id', $category->id )->first();
dd( $category->blog );
关于php - 如何使用 with 关键字在 Laravel 中获取数据和关系数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66507210/