【发布时间】:2017-06-01 17:25:42
【问题描述】:
我正在构建一个搜索功能,但我遇到了一个看似简单但显然很难的功能。
在搜索结果中,我已成功显示所有具有给定技能的用户。 (在这种情况下,它是belongsToMany()relationship),以及它们的first_name、last_name 和email。我希望条目的最后一部分显示用户在相关技能中的能力(在代码中称为skill_level)。目前,skill_level 是技能/用户关系的枢纽;它们由以下四个字符串之一表示:“Wants to Learn”、“Novice”、“Intermediate”、“Expert”,每个字符串的 id 为 1-4(含)。
以下是相关代码:
控制器(部分)
public function results(Request $request){
$theskillName = $request->input('theskillName');
$users = User::whereHas('skills', function ($q) use($theskillName) {
$q->where('name', '=', $theskillName);
})->get();
$skills = Skill::orderBy('name', 'ASC')->get();
if(count($users) > 0){
return view('search.search', compact('users', 'skills', 'theskillName'));
}
else {
return view ('search.search', compact('skills'));
}
}
search.blade.php(部分)
@if(isset($users))
<p>The following people have {{ $theskillName }} as one of their skills:</p>
<h2>People</h2>
<table class="table table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Skill Level</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{$user->first_name}}</td>
<td>{{$user->last_name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->???->skill_level }}</td> /* <- What replaces ??? here? */
</tr>
@endforeach
</tbody>
</table>
@endif
User.php(部分)
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id', 'first_name', 'last_name', 'middle', 'email', 'status', 'role', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'remember_token'
];
// Gets all of the skills the user knows
public function skills()
{
return $this->belongsToMany('App\Skill')->withPivot('skill_level');
}
到目前为止,我尝试的所有内容要么为条目的最后一部分返回null,要么吐出错误Trying to get property of non-object。谁能提供一些关于在这里做什么的见解?
更新:我尝试了明显的答案$user->pivot->skill_level,它给了我Trying to get property of non-object.
【问题讨论】:
-
搜索时添加pivot_column_name
-
所以我认为在你的情况下它会是 pivot_skill_level
标签: php laravel search pivot-table