查询从两个表使用laravel查询生成器+ mysql
问题描述:
我有两个表,一个叫做引号,另一个叫发票。我想检索所有没有发票的报价单。以下是我到目前为止的代码。我只能检索所有报价。我怎么能修改此查询查询从两个表使用laravel查询生成器+ mysql
$quotations = Quotation::lists('id', 'id');
mysql> describe quotations;
+--- ---- --------+------------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------------------+-----------------------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| customer_id | int(10) unsigned | NO | MUL | NULL | |
| employee_id | int(10) unsigned | NO | MUL | NULL | |
| exchange_rate | int(11) | NO | | 0 | |
| remark | varchar(255) | NO | | | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 | |
+---------------+------------------+------+-----+---------------------+-----------------------------+
mysql> describe invoices;
+--------------+------------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------------------+-----------------------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| quotation_id | int(10) unsigned | NO | MUL | NULL | |
| employee_id | int(10) unsigned | NO | MUL | NULL | |
| amount | int(11) | NO | | 0 | |
| balance | int(11) | NO | | 0 | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 | |
+--------------+------------------+------+-----+---------------------+-----------------------------+
答
您可以使用以下方法:
Quotation::has('invoices', '<', 1)->get();
这上面的代码假设你有你的Quotation
模型建立的关系,即:
class Quotation
{
public function invoices()
{
return $this->hasMany('\Models\Invoice');
}
}
has
方法将检查您已定义为第一个参数invoices
的关系中的项目总数。第二个参数是小于的比较,第三个是你想比较的数量。因此,这将搜索发票数量小于1的所有报价。
您可以阅读更多about querying relations here根据查询关系存在。
答
我把它加入感谢下面的代码Emn1ty
$quotations = Quotation::has('taxInvoices', '<', 1)->get();
感谢您的快速响应工作。请澄清你的答案。 '发票'不是一个属性。我想获取发票表 –
中没有条目的所有报价啊,我误读了关系。我会更新我的答案。 – jardis
感谢你的回答,你的回答是正确的,但你需要添加 - > get();为它工作。它应该像Quotation :: has('invoices',' get(); –