我如何使用 laravel 显示所有动物是狗的帖子

how can i display all posts where animal is dog using laravel

我有 2 tables 个帖子和动物,它们之间的关系是一到五月

帖子table: ID, animal_id

动物table: ID, 动物


动物模型:

public function posts()
{
    return $this->hasMany(Post::class);
}

Post 型号:

public function animale()
{
    return $this->belongsTo(Animal::class);
}

伪造者:

  public function definition()
{
    return [
        'animal' => $this->faker->randomElement(['Dog', 'cat', 'fish']),

    ];
}

看起来很简单,您只需传递动物的狗 ID table。

$dog = Post::where('animal_id',1)->get();

或者,如果您不知道 ID,请遵循以下方法

$dog = Post::whereHas('animals', function ($query) {
           $query->where('animal', 'Dog');
        })->get();

您有几种不同的方法可以做到这一点。您可以通过 Animal 模型,或通过 Post 模型:

通过Animal.php模型:

$posts = Animal::where('animal', 'Dog')->first()->posts;

通过Post.php模型:

$posts = Post::whereHas('animale', function ($query) {
  $query->where('animal', 'Dog');
})->get();

这些方法中的任何一种都将 return Post 个模型中的 Collection 个与 'Dog'Animal 模型相关。在另一个答案中使用 animal_id 的方法是有效的,但前提是您明确知道 'Dog'animals.id1。如果发生变化,则查询完全无效。