1

我有一个表格,我在其中提交来自“项目”的 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');
    }


}

提前致谢

4

1 回答 1

1

做了

<td>{{$task->project->proj_title}}</td>并且它应该可以正常工作,因为 Task 和 Project 有belongsTo关系,您应该能够获得与$taskusing相关的项目模型$task->project

于 2019-04-16T10:46:32.757 回答