[英]How can i get data by using "with" laravel relationship function by a condtion?
this is my table => table image这是我的桌子=> 桌子图片
//This is my controller
public function listUserStripeActionableRequests(Request $request) {
return $model = UserRequest::whereNull('deleted_at')
->with('oldPackage')
->get();
}
userRequest.php
public function oldPackage() {
return $this->hasOne(Package::class, 'id', 'old_package_id');
}
I need to get data according to package_type in the table if package_type == 1 then i need to get data from Package::class, if package_type == 2 then from AddOnsPackage::class then model function like :- $this->hasOne(AddOnsPackage::class, 'id', 'old_package_id');
我需要根据表中的 package_type 获取数据如果 package_type == 1 那么我需要从 Package::class 获取数据,如果 package_type == 2 然后从 AddOnsPackage::class 然后模型函数像 :- $this->hasOne(AddOnsPackage::class, 'id', 'old_package_id');
How can i use single query to get data accordingly?如何使用单个查询来相应地获取数据?
You can try你可以试试
class UserRequest extends Model
{
public function package()
{
return $this->hasOne(Package::class, 'id', 'old_package_id');
}
public function addon()
{
return $this->hasOne(AddonPackage::class, 'type', 'add_on_type');
}
public static function sorted()
{
return static::whereNull('deleted_at')
->get()
->map(function ($record) {
if ($record->package_type === 1) {
$record->load('package');
} elseif ($record->package_type === 2) {
$record->load('addon');
}
return $record;
});
}
}
Then in the controller you can do然后在控制器中你可以做
public function listUserStripeActionableRequests(Request $request)
{
return $model = UserRequest::sorted();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.