Laravel5.3 Eloquent Relationships没有得到确切的记录

时间:2017-03-27 13:39:35

标签: php laravel eloquent

我使用Laravel5.3 Eloquent Relationships从三个表中提取记录。

客户表:

Client Table

服务表: enter image description here

Subscribe_services表:

enter image description here

我想显示订阅服务的客户列表,但我没有获得服务名称我只从subscribe_service表获取数据

客户端型号:

    class Client extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $table = "clients";
    protected $fillable = [
        'name','country','place','mobile_no','email', 'password','api_token',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password'
    ];

        public function services()
    {
        return $this->hasMany('App\SubscribeService');
    }

客户端刀片:

 <select>
                    @foreach($user->services as $services)
                    <option>{{$services->service_id}}</option>
                    @endforeach
                  </select>

我如何获得服务名称?请提出任何建议

1 个答案:

答案 0 :(得分:0)

如果您想在此处使用hasMany(),请执行以下操作:

$client = Client::with('services.service')->find($id);

@foreach ($client->services as $service)
    {{ $service->service->name }}
@endforeach

要使这项工作正常,您应该将此关系添加到SubscribeService模型:

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

或者,您可以通过定义belongsToMany()关系来使用多对多关系。在这种情况下,您可以这样做:

$client = Client::with('services')->find($id);

@foreach ($client->services as $service)
    {{ $service->name }}
@endforeach