我遇到一个问题,当我在结果集中循环使用我正在预测的关系时。
这是目前的代码:
<?php
$deadlines = App\Deadlines::where('beginDatum', '<=', date("Y-m-d"))
->where('eindDatum', '>=', date("Y-m-d"))
->first();
$totalActivities = App\UserActivity::where('userid', Auth::id())
->where('deadline', '=', $deadlines->id)
->count();
if($totalActivities > 0) {
$activiteiten = \App\User::find(Auth::id());
foreach ($activiteiten->useractivities as $user_activity) {
if ($deadlines->id == $user_activity->deadline) {
print_r("<div class='col-md-4'><input type='text' value='$user_activity->datum' class='form-control'></div>");
foreach ($user_activity->activity as $activity) {
print_r("<div class='col-md-7'><input type='text' value='$activity->activiteit' class='form-control'></div>");
}
print_r("<div class='col-md-1'><input type='submit' class='btn btn-primary' value='Edit'></div>");
}
}
} else {
?>
<br/>U heeft nog geen activiteiten toegevoegd!
<?php
}
但是当存在重复的“活动”时,它会有一些奇怪的行为。在&#39; user_activity&#39;表。例如......
|--------------------------------------| | date | userid | activityid | |--------------------------------------| | 2017-12-28| 1 | 1 | | 2017-11-30| 1 | 1 | |--------------------------------------|
它有两个相同的activityid,所以活动的名称是相同的,但我不知道为什么它只显示重复活动的日期。当只有一个activityid条目时,它显示正常: https://gyazo.com/11cc6828f97e7a191bf40c8b74448e83
答案 0 :(得分:0)
你应该在这种查询中使用Laravel Eloquent多对多关系。
假设您正在使用Laravel 5.5,此文档条目将有所帮助:
https://laravel.com/docs/5.5/eloquent-relationships#many-to-many
基本上,在模型定义中,您应该建立关系。例如,在截止日期模型的定义中,您将具有以下内容:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Deadline extends Model
{
/**
* The activities associated with this deadline
*/
public function activities()
{
return $this->belongsToMany('App\UserActivity');
}
}
如果您为所有相关模型设置了此设置,那么您可以执行以下操作:
$user = App\User::findOrFail(Auth::id());
$today = date("Y-m-d");
$activities = $user->activities->whereHas('deadlines', function ($query) {
$query->where('beginDatum', '<=', $today)->where('eindDatum', '>=', $today;
})->get();