【发布时间】:2021-03-07 03:47:42
【问题描述】:
如何在查询中使用 with 从 Blogs 表中获取数据以及博客类别和博客标签。
下面是我的模型和控制器代码,我得到的是Get Blogs Api Error,而不是博客数据。
Blog 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);
}
}
Blog Model
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);
}
}
User Model
public function blog_user()
{
return $this->hasMany(Blog::class);
}
Blog Category Model
public function blog_category()
{
return $this->belongsTo(Blog::class);
}
Blog Tag Model
public function blog_tag()
{
return $this->belongsTo(Blog::class);
}
Blog Comment Model
public function blog_comment()
{
return $this->belongsTo(Blog::class);
}
Database table structure
blogs table structure
blog_categories table structure
blog_tags table structure
【问题讨论】:
-
错误日志是什么?在documentation 你需要使用 with([array])
-
@Atmahadli catch{} 正在执行,我尝试使用 with[array] 也 with(['category', 'tag', 'user', 'comment']),但同样的错误
-
我看到你捕获了 QueryException,那么实际的错误是什么?
-
@Atmahadli 尝试对 cmets、类别和标签使用复数。
-
@Atmahadli 没问题。我提出了一个解决方案。请检查