我正在建立一個汽車維修系統。每輛車都有一個或多個附件。每個車輛和組件都由一個賬戶「擁有」。用戶可能希望從車輛上拆下部件並將其放置在架子上,以便以後重新連接到同一輛或另一輛車上。該組件擁有一個vehicle_id字段,因此拆卸非常容易,我只需將vehicle_id字段置空,並且組件被有效「擱置」。先進的雄辯關係與樞軸?
我的困難在於找到可連接的組件來顯示可連接到選定車輛的擱架部件列表。 vehicle_types_component_types表是定義哪些組件類型可以附加到哪些車型的樞軸。某些組件類型可以安裝在多種車型上,每種車型都有一種或多種可以安裝的組件類型。
class VehicleType extends Eloquent {
public function ComponentTypes() { return $this->belongsToMany('ComponentType', 'vehicle_types_component_types')->withTimestamps(); }
}
class Vehicle extends Eloquent {
public function Account() { return $this->belongsTo('Account', 'account_id'); }
public function VehicleType() { return $this->belongsTo('VehicleType', 'vehicle_type_id'); }
public function Components() { return $this->hasMany('Component'); }
}
class ComponentType extends Eloquent {
public function VehicleTypes() { return $this->belongsToMany('VehicleTypes', 'vehicle_types_component_types')->withTimestamps(); }
public function Components() { return $this->hasMany('Component'); }
}
class Component extends Eloquent {
public function Account() { return $this->belongsTo('Account', 'account_id'); }
public function Vehicle() { return $this->belongsTo('Vehicle', 'vehicle_id'); } // This is null when component is not attached to vehicle
public function ComponentType() { return $this->belongsTo('ComponentType', 'component_type_id'); }
}
所以說我希望做的是找到屬於指定ACCOUNT_ID的所有組件,並且有一個空vehicle_id,並在組件的組件類型的車輛類型爲「安裝」中的定義, vehicle_types_component_types數據透視表。最重要的是,我還需要通過其組件類型排除某些組件......例如,component_type!='tire'。
我已經試過了顯然是行不通的,但應證明什麼,我試圖做...
public function findAttachable($vehicle_type_id, $account_id)
{
return Component::with('ComponentType')
->where('vehicle_id', null)
->where('account_id', $account_id)
->where('vehicle_type_component_type.vehicle_type_id', $vehicle_type_id)
->where('vehicle_type_component_type.component_type_id', 'components.components_type_id')
->where('component_types.type', '!=', 'tire');
}
如果有東西像「withPivot」方法什麼的,那會真的很酷...
$components = Component::where('vehicle_id', null)
->where('account_id', $account_id)
->withPivot('component_type_id', $vehicle_type_id);
任何幫助,將不勝感激!提前致謝。