[英]Laravel: One to Many relationship, pull last N record from table
I have a User model and workLOG model.我有一个用户 model 和 workLOG model。 The user model has many work logs, meaning One user can have many work logs (ONE TO MANY RELATIONSHIP).
用户 model 有很多工作日志,这意味着一个用户可以有很多工作日志(一对多关系)。 I have created a relationship using the Eloquent relationship.
我使用 Eloquent 关系创建了一个关系。
User Model用户 Model
public function workLog()
{
return $this->hasMany('App\WorkLog','user_id','id');
}
workLog Model工作日志 Model
class WorkLog extends Model
{
protected $table="worklog";
}
The worklog table has a column called total_hours_per_day
.工作日志表有一个名为
total_hours_per_day
的列。 How can I pull the last N records from the column of the logged-in or authenticated user?如何从已登录或已验证用户的列中提取最后 N 条记录?
What I have done to get workLog so far到目前为止,我为获得 workLog 所做的工作
$worklogs = Auth::user()->workLog;
Now I want to get last 7 data from the column total_hours_per_day
现在我想从
total_hours_per_day
列中获取最后 7 个数据
you need to establish on the WorkLog
model a belongsTo
.您需要在
WorkLog
model 上建立一个belongsTo
。
public function user()
{
return $this->belongsTo('App\User');
}
Edit: relationships have to be established in both models you're trying to relate.编辑:必须在您尝试关联的两个模型中建立关系。 If you like a girl, she needs to like you back to establish a relationship.
如果你喜欢一个女孩,她需要重新喜欢你才能建立关系。 You just defined the relationship in one side.
您只是在一侧定义了关系。
$worklogs = Auth::user()->workLog->take(-7)->reverse();
and I pull the last 7 records from total_hours_per_day
column in the blade template as:-我从刀片模板中的
total_hours_per_day
列中提取最后 7 条记录:-
@foreach ($worklogs as $worklog)
{{ $worklog->total_hours_per_day }}
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.