使用laravel query builder + mysql从两个表中查询

时间:2016-01-31 01:06:30

标签: laravel laravel-query-builder

我有两个表,一个叫引号,另一个叫发票。我想要在没有发票的情况下检索所有报价。下面是我到目前为止的代码。我只能检索所有报价。如何修改此查询

$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 |                             |
+--------------+------------------+------+-----+---------------------+-----------------------------+

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

Quotation::has('invoices', '<', 1)->get();

以上代码假设您在Quotation模型中设置了关系,即:

class Quotation 
{
    public function invoices()
    {
        return $this->hasMany('\Models\Invoice');
    }
}

has方法将检查您已定义为第一个参数invoices的关系中的项目总数。第二个参数是小于的比较,第三个是要比较的计数。因此,这将搜索发票数少于一的所有报价。

您可以在查询关系存在下阅读更多about querying relations here

答案 1 :(得分:0)

由于Emn1ty

,我在下面添加了代码
$quotations = Quotation::has('taxInvoices', '<', 1)->get();