Laravel多个模型关联使用的情况

比如说有三个模型,我想实现这样的效果:

SELECT DISTINCT `platforms`.* 
FROM `company_products` 
INNER JOIN `platforms` 
    ON `company_products`.`platform_id` = `platforms`.`id` 
WHERE `company_products`.`onboard_company_id` = 27 
    AND `company_products`.`product_type` LIKE 'TABF-Import%' 

  在下面可以这样实现:platformsImport

OnboardCompany
<?php
namespace App\Models;
use App\Models\Enums\StatusEnum;

class OnboardCompany extends Model
{

    public function product()
    {
        return $this->hasMany(CompanyProduct::class, "onboard_company_id", "id")->where('status', StatusEnum::Valid);
    }

    public function platformsImport()
    {
        $platforms = $this->product()
            ->where('product_type', 'like', 'TABF-Import%')
            ->whereHas('platform', function ($query) {
                $query->where('status', 1);
            })
            ->get()
            ->map(function ($item) {
                return $item->platform;
            });

        return $platforms;
        // $query = $this->getConnection()->table('company_products')
        //     ->join('platforms', 'company_products.platform_id', '=', 'platforms.id')
        //     ->where('company_products.onboard_company_id', '=', $this->id)
        //     ->where('company_products.product_type', 'like', 'TABF-Import%')
        //     ->where('platforms.status', '=', 1)
        //     ->select('platforms.*')
        //     ->distinct();
            
        // return $query->get();
    }
}

  

CompanyProduct:
<?php

namespace App\Models;

use App\Models\Enums\StatusEnum;

class CompanyProduct extends Model
{
    public function platform()
    {
        return $this->hasOne(Platform::class, 'id', 'platform_id');//->where('status', StatusEnum::Valid);
    }
}

  

Platform:
<?php

namespace App\Models;

use App\Traits\AuditTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Platform extends Model
{
    use HasFactory;
    use \App\Traits\AuditTrait;
    
    protected $guarded = [];

    const TYPE = [
        1 => 'Platform',
        2 => 'Partner',
    ];



}

  


posted @ 2023-06-07 16:00  爱家家的卡卡  阅读(80)  评论(0编辑  收藏  举报