我有一个表单,其中我从“项目”中提交了ID;
<div class="form-group">
<label for="Project">Project</label>
<select name="proj_id" class="form-control">
@if (count($project) == 0)
<option>There are no projects.</option>
@else
@foreach($project as $project)
<option value="{{$project->proj_id}}">{{$project->proj_title}}</option>
@endforeach
@endif
</select>
</div>
这部分正常工作,它将proj_id插入数据库,但是当我返回索引时,我想从该ID中显示项目的名称。 这是我的索引;
<tbody class="">
@foreach ($task as $task)
<tr>
<td>{{$task->task_id}}</td>
-------> <td>{{$projects->find($task->proj_id)->proj_title}}</td>
<td>{{$task->task_title}}</td>
<td>{{$task->task_desc}}</td>
<td>{{$task->status}}</td>
<td>{{$task->priority}}</td>
<td>{{$task->created_by}}</td>
<td>{{$task->created_at}}</td>
@if (Auth::user()->role=='admin')
<td>
就这样,它给了我标题错误。
如果我用$task->proj_id
更改该行,则显示该行没有问题。
这也是TaskController中的索引函数:
public function index()
{
return view('tasks.index', [
'task' => Task::all(),
'projects' => Project::all(),
]);
}
这些是我的关系: 项目模型;
class Project extends Model
{
protected $primaryKey = 'proj_id';
protected $fillable = ['proj_title','proj_desc','client_id','created_by'];
public function client (){
return $this->belongsTo('App\Client');
}
public function tasks (){
return $this->hasMany('App\Task');
}
}
任务模型;
class Task extends Model
{
protected $primaryKey = 'task_id';
protected $fillable = ['task_title','task_desc','status','priority','person_id','proj_title','proj_id','created_by'];
public function project(){
return $this->belongsTo('App\Project','proj_id');
}
}
预先感谢
答案 0 :(得分:1)
做到
<td>{{$task->project->proj_title}}</td>
,它应该可以正常工作,因为“任务”和“项目”具有belongsTo
关系,您应该能够使用$task
获取与$task->project
相关的Project模型。