使用Eloquent查询相关表数据

时间:2017-01-06 15:39:25

标签: laravel eloquent query-builder

我在尝试从基于相关表的模型中获取记录时遇到问题。

我有两个名为$id_combination = $product->addCombinationEntity($wholesale_price, $price, $weight, $unit_price_impact, 0, $quantity, $ids_image, $reference, 0, $ean13, 0, 0, $upc); foreach ($product_option_value as $id_attribute) { Db::getInstance()->execute('INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $id_attribute. ',' . (int) $id_combination . ')'); } 的表和一个名为leads的表,我的应用程序基本上每月一次在recycle_logs表中发送相同的记录,当它这样做时将在leads中存储新记录。

问题在于,我需要选择具有特定recycle_logs值且具有与leads不同的特定campaign_id的所有status,目前为止一切顺利,现在问题是我只有在没有任何invalid与之关联的情况下才能获取它们或者如果与该特定recycleLogs相关联的最后一个recycleLog早于{{1}例如,几天前。

我目前看起来有点像这样。

lead

我究竟做错了什么?无论我添加或删除30

,它总是选择相同数量的记录

我已经设法通过原始SQL查询来完成它,我将在下面发布,以防它帮助任何人,我仍然想知道如何在Eloquent / Query Builder中执行它。

    $leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
                ->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
                ->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
                ->orderBy(Lead::CREATED_AT, 'desc')
                ->with(
                    ['leadRecyclingLog' => function($query) {
                        $query->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays))
                            ->orWhere(LeadRecyclingLog::ID, null);
                    }]
                )
                ->get();

2 个答案:

答案 0 :(得分:1)

试试这个:

$leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
    ->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
    ->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
    ->orderBy(Lead::CREATED_AT, 'desc')
    ->where(function($q) {
        $q->whereHas('leadRecyclingLog', function($q) {
            $q->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays));
        })
        ->orWhereHas('leadRecyclingLog', '<', 1); // Where count of the relationship is smaller than 1
    })->get();

我假设查询的第一部分运行良好(直到关系)。

您要找的是->whereHas(relationship),而不是->with(relationship)->with(relationship)会将相关结果附加到原始模型(原始模型的查询不会受->with()影响)。 ->whereHas(relationship)按条件过滤原始模型。

答案 1 :(得分:1)

通过@devk的帮助

了解它
    $leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
        ->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
        ->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
        ->orderBy(Lead::CREATED_AT, 'desc')
        ->where(function($q) {
            $q->whereHas('leadRecyclingLog', function($q) {
                $q->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays));
            })
                ->doesntHave('leadRecyclingLog', 'or');
        })->get();