提交用户ID并显示用户名?

时间:2019-04-15 15:59:23

标签: php laravel

我收到了这张表格

fetch first 1 row only

将数据发送到此控制器

    <div class="form-group">
        <label for="clientId">Client</label>
        <select name="client_id" class="form-control">

            @if(count($client) == 0)
            <option>There are no clients.</option>
            @else
                @foreach($client as $client)
                    <option value="{{$client->client_id}}">{{$client->client_name}}</option>
                @endforeach
            @endif

        </select>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-success">Submit</button>
    </div>

我已经完成了从客户到项目的一对多关系。

我的意图是您提交client_id,将其插入数据库,然后在索引上看到与该client_id相关的client_name。

这是我的索引

public function store(Request $r)
    {

        $validatedData = $r->validate([
            'proj_title' => 'required|max:100',
            'client_id' => 'required',
            'proj_desc' => 'required',
        ]);


        $currentUserId = Auth::user()->user_id;
        $currentUser = User::find('username')->name;

        $r['created_by'] = $currentUser;

        $project = Project::create($r->all());
        return redirect('/projects')->with('store','');
    }

这些是我的关系: 项目模型:

<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>Project Id</th>
            <th>Title</th>
            <th>Description</th>
            <th>Client</th>
            <th>Created by</th>
            <th>Created on</th>
            @if (Auth::user()->role=='admin')
            <th>Admin</th>

            @endif
        </tr>

    </thead>
    <tbody class="">
        @foreach ($project as $project)
        <tr>
            <td>{{$project->proj_id}}</td>
            <td>{{$project->proj_title}}</td>
            <td>{{$project->proj_desc}}</td>
            <td>{{$client->client_name}}</td>
            <td>{{$project->created_by}}</td>
            <td>{{$project->created_at}}</td>

客户:

class Project extends Model
{
    protected $primaryKey = 'proj_id';
    protected $fillable = ['proj_title','proj_desc','client_id','created_by'];

     public function user()
    {
        return $this->hasOne('App\User');
    }

    public function task()
    {
        return $this->hasMany('App\Task');
    }
public function client()
    {
        return $this->hasOne('App\Client');
    }
}

现在,我得到“此集合实例上不存在属性[client_name]。(查看:D:\ Programas \ xampp \ htdocs \ test5 \ resources \ views \ projects \ index.blade.php) “

关系仍然让我感到困惑,如果这是一个非常愚蠢的问题,请对不起。

预先感谢

1 个答案:

答案 0 :(得分:0)

客户关系:

public function client()
{
    return $this->belongsTo('App\Client');
}

项目关系:

public function projects()
{
    return $this->hasMany('App\Project','proj_id');
}

要获取客户名称,只需使用$project->client->client_name,顺便说一句。使用复数,学习正确编写代码...