2 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用 Eloquent 來實(shí)現(xiàn)此目的,而不是使用左連接和數(shù)據(jù)庫外觀。
我猜公司和Logo之間的關(guān)系是1:1或1:n。如果我們假設(shè)它是 1:1 那么你的查詢將如下所示:
Company::whereHas('logo', function($query) {
? ? return $query->where('date', '<', Carbon::now()->subDays(90));
})->orWhereDoesntHave('logo')->...
您應(yīng)該檢查:查詢關(guān)系缺失
只要我們遵循 Laravel 命名約定,我們就不需要指定表名,Laravel 會從模型名稱中找出它。
標(biāo)志模型應(yīng)該是這樣的:
class Logo extends Model
{
? ? // protected $table = 'logos';?
? ? // not necessary, Laravel already knows to use logos table
? ? protected $guarded = ['id'];
? ? public function company()
? ? {
? ? ? ? // return $this->belongsTo(Company::class, 'companies_id');
? ? ? ? // no need to specify foreign key if we follow naming convention
? ? ? ? // foreign key should be {foreign_model_singular}_id
? ? ? ? // in this case it is company_id
? ? ? ? return $this->belongsTo(Company::class);
? ? }
}
Company 模型也不需要指定表名,它已經(jīng)知道它應(yīng)該是Companies。
公司模式:
class Company extends Model
{
? ? // protected $table = 'companies';
? ? protected $guarded = ['id'];
? ? public function logo()
? ? {
? ? ? ? return $this->hasOne(Logo::class);
? ? }
}
請檢查 $guarded 和 $fillable 屬性如何工作。如果只有id設(shè)置為受保護(hù),則所有其他屬性均不受保護(hù),不確定這是否是您的意圖。
完整的查詢應(yīng)該是:
Company::whereHas('logo', function($query) {
? ? return $query->where('updated_at', '<', Carbon::now()->subDays(90));
})->orWhereDoesntHave('logo')
->orderBy('name', 'ASC')
->get();

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
->whereDate('logos.updated_at' whereDate 僅比較 dateTime 列的日期部分 ... 嘗試使用 Carbon 的 toDateString() ...
$symbolsWithoutLogos = DB::table('companies')
->leftJoin('logos', 'companies.id', '=', 'logos.companies_id')
->whereDate('logos.updated_at', Carbon::now()->subDays(90)->toDateString())
->whereNull('companies.logo_image')
->orderBy('name', 'ASC')->select('companies.*')
->get();
- 2 回答
- 0 關(guān)注
- 166 瀏覽
添加回答
舉報(bào)