l5-repository
l5-repository copied to clipboard
RequestCriteria supports for Morph relationship
Problem
Query for morphTo relationship will get an exception of "Please use whereHasMorph for morph relationship" error.
Idea of change
Add new condition for a bit more complex setups as array.
// Example, the data relationship has different morph types for purpose, and we can specify a condition as array for those needed parameters.
public ProductRepository extends BaseRepository {
protected $fieldSearchable = [
'product_name' => 'like',
'data.category' => [
'relationType' => 'morph',
'condition' => '=',
'types' => [Turnkey::class, Pcba::class, Pcb::class, MouldTooling::class, Accessory::class],
],
];
// Changed RequestCriteria class
// patch for morph relationship query
if (is_array($condition)) {
$types = $condition['types'];
$relationType = $condition['relationType'];
$condition = $condition['condition'];
}
$condition = trim(strtolower($condition));
if(!is_null($relation)) {
$callback = function($query) use($field,$condition,$value) {
if($condition === 'in'){
$query->whereIn($field,$value);
}elseif($condition === 'between'){
$query->whereBetween($field,$value);
}else{
$query->where($field,$condition,$value);
}
};
// patch example for morph relation
if (!is_null($relationType) && $relationType == 'morph') {
$query->whereHasMorph($relation, $types, $callback);
// $query->orWhereHasMorph($relation, $types, $callback); // when it shall be OR..
} else {
$query->whereHas($relation, $callback);
}
}
Commenting
The idea code is just an example for describing the idea, this issue could be used to discuss if any potential problem of this change and recommendations.