我想基于project_id从表Tasks中获取记录。但是我找不到我想要的结果。 我的项目模型代码:
class Project extends Model
{
function progress(){
return $this->hasMany(Progress::class);
}
}
进度模型代码:
class Progress extends Model
{
function project(){
return $this->belongsTo(Project::class);
}
function task(){
return $this->hasMany(Task::class);
}
}
任务模型代码:
class Task extends Model
{
protected $fillable = [
'progress',
];
function progress(){
return $this->belongsTo(Progress::class, 'id');
}
}
这是我的控制器功能:
public function task_project_view_detail($id){
$project = Project::with(['user', 'image', 'document', 'progress.task'])->where('id', $id)->first();
$progress = $project->progress;
return view('admin.tasks.project-view', ['progress' => $progress])->with('project', $project);
}
这是我的查看文件:
@foreach ($progress as $prog)
@foreach ($prog->task as $tasks)
<li class="task">
<div class="task-container">
<span class="task-action-btn task-check">
<a href="" style="background:#3d981f;" class="action-circle large complete-btn" title="Mark Complete">
<i class="material-icons">check</i>
</a>
</span>
<span class="task-label" contenteditable="true">{{ $tasks->name }}</span>
<span class="task-action-btn task-btn-right">
<a href="" class="action-circle large" title="Delete Task">
<i class="material-icons">delete</i>
</a>
</span>
</div>
</li>
@endforeach
@endforeach
这是我的结果: there should be only first 3 rows, but all tasks in this project are showing.
There should be only 1 row, the 4th one.
这是项目模型的架构:
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->string('title');
$table->timestamps();
});
这是进度模型的模式:
Schema::create('progress', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('project_id')->nullable();
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade')->onUpdate('cascade');
$table->string('name');
$table->timestamps();
});
这是任务模型的架构:
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('progress_id')->nullable();
$table->foreign('progress_id')->references('id')->on('progress')->onDelete('cascade')->onUpdate('cascade');
$table->string('name')->nullable();
$table->string('status')->nullable();
$table->timestamps();
});
我该怎么办?
答案 0 :(得分:0)
has-many-through
关系为通过中间关系访问远处的关系提供了方便的快捷方式。在您的情况下,您可以这样使用:
在项目模型中定义tasks()
:
public function tasks()
{
return $this->hasManyThrough('App\Task', 'App\Progress');
}
传递给hasManyThrough
方法的第一个参数是我们希望访问的最终模型的名称,而第二个参数是中间模型的名称。
要获得项目任务,您可以在控制器中执行以下操作:
public function task_project_view_detail($id){
$project = Project::with(['user', 'image', 'document', 'tasks'])->where('id', $id)->first();
$tasks= $project->tasks;
return view('admin.tasks.project-view', ['tasks' => $tasks])->with('project', $project);
}
然后在视图中直接使用foreach
,如下所示:
@foreach ($tasks as $task)