我有两个具有多到多关系的模型,在枢轴表上有一些附加字段:
Shift table:
------------
id - uuid
date - date
address - string
...
Employee table:
---------------
id - uuid
first_name - string
...
shift_employee table:
---------------------
id - integer
shift_id - uuid
employee_id - uuid
hours_worked - integer
...现在,我在Laravel中制作一个透镜,我想使用查询对象来检查shift_employee上任何与特定移位相关的实例,对于shift_employee表中的hours_worked,其值是否大于0。
我的第一个想法是以某种方式使用whereHas,假设Shift模型有关系员工,如下所示:
$query->whereHas('employees' function ($q) {
$q->where('hours_worked', '>', 0);
});但是..。这不管用..。对于某些员工,有超过0 hours_worked的轮班,这个查询字符串不适用于我。我该怎么做?
发布于 2021-04-27 21:43:40
首先,确保您的模型建模正确。如果是的话,您可以访问中间表的任何属性,如下所示:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\User');
}
}例:
$user = App\User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}在你的例子中,试着:
$employee = Employee::with('Shift');
foreach($employee as $e){
$employeeHw[] = $e->shift_employee->where('hours_worked', '>', 0)->get();
}我对laverel也很陌生,所以我不确定它是否有效,但理论上:P--通常在这些情况下,我使用的是查询bilder和join,我觉得这更容易
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();https://stackoverflow.com/questions/67286546
复制相似问题