php - 如何使用 with 关键字在 Laravel 中获取数据和关系数据?

标签 php laravel eloquent

如何在查询中使用 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表结构

Blogs table structure

blog_categories 表结构

Blog Category

blog_tags表结构

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/

相关文章:

PHP pdo - 许多连接

Javascript/PHP - 将数据传递到模态(弹出窗口)

php - Laravel 5.8 自定义表单请求未按预期工作?

Laravel:重定向到另一个需要 POST 变量的 Controller

php - 获取 UTF-8 字符串的第一个字符

php - 将字符串转换为变量

php - 如何检查条件是否为真然后在竞争条件下插入一些东西

php - 如何在相关 ORM Laravel 的 json 对象中选择数据写入位置

php - 使用 Laravel 模型过滤数据透视表数据

php - 拉维尔 : Eloquent Skip records