首页 > 解决方案 > 通过属性访问另一个表

问题描述

我在模型中定义了从另一个表中获取数据的属性,但是我没有定义这两个表之间的关系:

租赁请求模型

public function getSecurityDepositEntryAttribute() {
    return Rent::where([
        ['property_id', $this->property_id],
        ['lease_request_id', $this->id],
        ['type', 'security_deposit_migration'],
    ])->orderBy('created_at', 'asc')->first();
}

我现在可以LeaseRequest使用此属性过滤表吗?我试过这个,但得到BadMethodCallException

LeaseRequest::whereHas('security_deposit_entry', function($query) {
    $query->whereColumnNotIn('status', ['refund_in_process', 'refunded']);
})->get();

如果这是不可能的,我可以用where属性中的预定义子句定义这两个表之间的关系吗?

标签: laravel

解决方案


不,不可能,您必须使用关系并使用compoships lib

public function rent() {
    return $this->hasOne(Rent::class,['lease_request_id','property_id'],['id','property_id'])
   ->where('type', 'security_deposit_migration')
   ->orderBy('created_at', 'asc');
}

['lease_request_id','property_id'] 是外键

['id','property_id'] 是本地键

那么你可以使用 whereHas


推荐阅读