Select 不在关系中的记录 table
Select records where not in relational table
我有 2 个具有这种结构的表:
**table1**
id | title
-----+--------
1 | Blah1
2 | Blah2
**table2**
id | table1_id | article_id
-----+-------------+------------
1 | 1 | 1
2 | 1 | 3
3 | 2 | 1
现在我想知道如何 select table1
中未在 table2
中使用的所有记录
例如,我需要 table2
中不存在的所有 table1
记录用于 article_id=3
如何创建模型并使用 eloquent 模型?
更新:
我需要 table1
的 Blah2
然后显示给我的用户,因为 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 => 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();
以上查询应该 return 需要的结果。
我有 2 个具有这种结构的表:
**table1**
id | title
-----+--------
1 | Blah1
2 | Blah2
**table2**
id | table1_id | article_id
-----+-------------+------------
1 | 1 | 1
2 | 1 | 3
3 | 2 | 1
现在我想知道如何 select table1
中未在 table2
例如,我需要 table2
中不存在的所有 table1
记录用于 article_id=3
如何创建模型并使用 eloquent 模型?
更新:
我需要 table1
的 Blah2
然后显示给我的用户,因为 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 => 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();
以上查询应该 return 需要的结果。