[英]Laravel use model property in relation method
我有一個模型的關系方法,它對模型本身的屬性(created_at)進行了比較。 我想將“約會”模型的 created_at 日期與“治療”的 created_at 日期進行比較。 如果“created_at”日期晚於“約會”日期,我只想要“治療”
約會控制器.php
public function index(): JsonResource
{
$users = User::with([
'appointment' => function ($query) {
$query->with(['appointment_events']);
},
])
->active()
->get();
return UserResource::collection($users);
}
約會.php
public function appointment_events(): HasMany
{
return $this->hasMany(AppointmentEvent::class)
->with([
'customer' => function ($query) {
$query->with([
'section' => function ($subquery) {
$subquery
->with([
'advice',
'treatment' => function ($subquery) {
$subquery->where('created_at', '>', blank); //How can I get the model's created_at date.
},
]);
},
]);
},
]);
}
有沒有辦法做到這一點?
我認為您應該將查詢移至Appointment模型的范圍並保持關系定義簡單。
注意:下面假設表名和列名符合標准 Laravel 約定。 如果您有不同的約定,請相應地修改表名和列名。
class Appointment extends Model
{
public function scopeWithFutureTreatments($query)
{
return $query->with([
'appointment_events' => function($query) {
$query->with([
'customers' => function($query) {
$query->with([
'section' => function($query) {
$query->with([
'advice',
'treatment' => function($query){
$query->join('sections', 'section.id', '=', 'treatments.section_id')
->join('customers', 'customers.id', '=', 'sections.customer_id')
->join('appointment_events', 'appointment_events.id', '=', 'customer.appointment_events_id')
->join('appointments', 'appointments.id', '=', 'appointment_events.appointment_id')
->whereColumn('treatments.created_at', '>', 'appointments.created_at')
->select('treatments.*')
}
]);
}
]);
}
]);
}
]);
}
public function appointment_events(): HasMany
{
return $this->hasMany(AppointmentEvent::class);
}
}
然后在AppointmentController中,以下內容應該可以為您提供所需的結果
public function index(): JsonResource
{
$users = User::with([
'appointment' => function ($query) {
$query->withFutureTreatments();
},
])
->active()
->get();
return UserResource::collection($users);
}
如果我理解你的關系是
用戶 ->HasManyAppointments ->HasManyAppointmentsEvents。
您可以直接訪問來自用戶的約會事件數據
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get all of the appointment_events for the user.
*/
public function appointment_events()
{
return $this->hasManyThrough(Appointment::class, AppointmentEvent::class);
}
}
所以可以查詢
$collection = User::with(['appointments','appointment_events'])->where()->get();
它為您提供特定用戶的所有約會和相關的約會事件。 您可以點擊該集合或過濾器或您想要的任何業務邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.