php - Laravel Eloquent 在父表中有很多条件

标签 php laravel eloquent

我有这些表:

  1. 地点
    • id
    • 姓名
    • 地址
  2. 用户
    • id
    • 姓名
    • 电子邮件
  3. 评论
    • id
    • place_id
    • user_id
    • 标题
    • 审核
    • as_anoniem

即使 as_anoniem1user_id 也会被填充。

现在我想要所有 places 的所有 reviewsuser 除了那些 as_anoniem = 1

像这样:

Place::with(['review' => function ($query) {
    return $query->with('user')->where('as_anoniem', 1);
}]);

这并不完全正确,因为它仅返回 as_anoniem = 1reviews

如何使用 实现此目的? ?

最佳答案

你可以试试这个:

$users = \App::User::with('reviews' => function($query) {
    $query->where('as_anoniem', '!=', 1);
})->get();

这将要求您在App\User 模型中创建一个一对多 关系,例如:

// App\User.php
public function reviews()
{
    // namespace: App\Review
    return $this->hasMany(Review::class);
}

假设UserReview 的命名空间都是App,它们在同一个目录中。

更新原问题被OP修改后:

$places = \App::Place::with('reviews' => function($query) {
    $query->with('user')->where('reviews.as_anoniem', '!=', 1);
})
->get();

放置模型:

public function reviews()
{
    // namespace: App\Review
    return $this->hasMany(Review::class);
}

审核模型:

public function user()
{
    // namespace: App\User
    return $this->belongsTo(User::class);
}

关于php - Laravel Eloquent 在父表中有很多条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36195777/

相关文章:

php - 从 php 调用 js 函数时出现问题

PHP - uniqid() 会生成字母 ID 吗?

laravel - 如何在 laravel eloquent 中选择特定列

php - 如何在 Eloquent 中找回小写的列名?

php - 如何禁用updated_at的时间戳值?

php - 使用 while 循环插入表

php - 在哪里指定 Laravel 应用程序的应用程序版本?

php - Laravel 5.5 ThrottleRequest 中间件

php - 在 Laravel Eloquent ORM 中处理 Mysql Spatial 数据类型

laravel - 如何在 Laravel 中取消多个文件的链接