【发布时间】:2018-07-18 07:33:43
【问题描述】:
我在 laravel 中建立了多对多关系,它工作正常,但是当我想检索并显示我的数据时,会发生一些奇怪的事情 现在我想显示分配给登录用户的客户端所以这是我的代码 客户端模型:
public function sellmanlist(){
return $this->belongsToMany('App\User' , 'client_user','client_id');
}
控制器和获取方法
public function myclient(Client $client){
$user_id =Auth::user()->id;
$client = Client::with('sellmanlist')->firstOrFail();
return view('admin.client.myclient',compact('user_id','client'));
}
这是我已经在测试的视图
@foreach($client->sellmanlist as $sellman )
@php(
$sell_id = $sellman->pivot->user_id
)
@if($user_id === $sell_id)
{{$client->id}}
{{$client->title}}
<br>
@endif
@endforeach
但这仅显示 1 2 次的客户端 ID,这是我的数据透视表
public function up()
{
Schema::create('client_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('client_id');
$table->integer('user_id');
$table->timestamps();
});
}
【问题讨论】:
-
您可以在您的问题中添加您的
User模型及其关系吗? -
我应该在 usermodel 上定义 viseversa 关系吗?喜欢有很多客户吗?因为我对我的用户模型没有任何了解,但每件事都在保存和更新数据
-
如果在用户模型
belongsToMany添加关系会更好 -
我已经添加了答案检查一次