【问题标题】:Select records where not in relational table选择不在关系表中的记录
【发布时间】:2016-11-29 10:04:27
【问题描述】:

我有 2 个具有这种结构的表:

**table1**
id   |  title
-----+--------
 1   |  Blah1
 2   |  Blah2

**table2**
id   |  table1_id  | article_id
-----+-------------+------------
 1   |   1         |  1
 2   |   1         |  3
 3   |   2         |  1

现在我想知道如何从table1 中选择在table2 中不使用的所有记录

例如,对于article_id=3,我需要table2 中不存在的所有table1 记录

如何创建模型并使用 eloquent 模型?

更新:

我需要来自table1Blah2,然后显示给我的用户,因为Blah1 之前插入了article_id = 3

更新 2:

这是有效的查询,我需要为此查询编写模型:

SELECT a.*
FROM table1 AS a
WHERE a.id NOT IN (SELECT table1_id
FROM table2
WHERE article_id = 3
)

【问题讨论】:

  • 你能更准确地解释一下你在找什么吗?如果您至少不能更新您的问题并为您的预期输出设计一个架构,就像您已经为 table1 和 table2 提供的那样。
  • @MahfuzulAlam 我更新了我的问题
  • @MajAfy:您想从表 1 中获取其 id 在表 2 中不可用的记录作为 article_id 字段。表示你想要id |标题 ----------------- 2 | Blah2 因为 2 在表 2 中不能作为 article_id 使用,对吧?
  • @DeepakDixit 是的,完全正确
  • @DeepakDixit 我添加了一个示例查询

标签: laravel laravel-5.3


【解决方案1】:

您需要创建类似下面的模型,您可以适当地更改名称 在这里,我将参考以下内容 table1 => ParentModel 和 table2 => ChildModel

使用以下方法在 ParentModel 中定义孩子的关系

class ParentModel extends Model {
    public function children() {
        return $this->hasMany(ChildModel::class, 'table1_id');
    }
}

whereDoesntHave 方法可用于过滤具有相关模型的记录 在这里查看https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-absence

ParentModel::whereDoesntHave('children', function($q){
     // here $q refers to related model in this case ChildModel
     $q->where('article_id', 3); 
})->get();

上面的查询应该返回所需的结果。

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2021-12-30
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多