【问题标题】:How to fetch data along with relationship data in Laravel using with keyword?如何使用 with 关键字在 Laravel 中获取数据和关系数据?
【发布时间】: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 尝试对 cme​​ts、类别和标签使用复数。
  • @Atmahadli 没问题。我提出了一个解决方案。请检查

标签: php laravel eloquent


【解决方案1】:

首先将名称更改为复数。不是单数。当您使用一对多时。并使用 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 );

【讨论】:

  • 感谢更新,但我的输出不应依赖于任何类别,它应该是所有博客以及每个博客相关数据,如 cmets、标签、类别。我正在使用with 关键字查询。
  • 使用这个查询。 $blogs = Blog::with('categories')->get();
猜你喜欢
  • 2021-07-08
  • 2021-03-05
  • 2020-11-07
  • 2018-10-24
  • 2020-11-27
  • 1970-01-01
  • 2019-09-12
  • 2021-02-09
  • 2020-07-01
相关资源
最近更新 更多