Laravel一对多关系问题

时间:2019-07-16 14:19:13

标签: laravel laravel-5 eloquent

我正在研究laravel v5.8项目。我在建立一对多关系时遇到一些问题。

我有两个表,一个是提供某些服务的用户,另一个是提供表服务的用户。我想在它们之间建立一对多的关系。 用户必须拥有许多服务。 服务必须属于用户。 我的代码:

User.php

public function services()
    {
        return $this->hasMany(Service::class);
    }

Service.php

public function user()
    {
        return $this->belongsTo(User::class);
    }

Controller.php

 public function index()
    {
        //
        return view('vendor.services',['services'=>Service::with("user")->get()]);
    }

刀片文件

 @foreach ($services as $service )
    <tr>
      <td>{{$service->name}}</td>
      <td>{{$service->user_id->name}}</td>
    </tr>
 @endforeach

移民 1.用户

 Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

2.services

Schema::create('services', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string("short_desc", 250);
            $table->string("long_desc", 1500);
            $table->double("price", 10);
            $table->bigInteger('type_id')->unsigned();
            $table->foreign('type_id')->references('id')->on('types');
            $table->string("img");
            $table->bigInteger("city_id")->unsigned()->nullable();
            $table->foreign('city_id')->references('id')->on('cities');
            $table->bigInteger("region_id")->unsigned()->nullable();
            $table->foreign('region_id')->references('id')->on('regions');
            $table->bigInteger("user_id")->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });

错误: 试图获取非对象的属性“名称”(查看:/home/nazeeh/Desktop/petVet/resources/views/vendor/services.blade.php)

1 个答案:

答案 0 :(得分:2)

替换

{{$service->user_id[0]??'not'}}

使用

{{$service->user ? $service->user->name : 'not'}}

您可以显示users表中的任何字段,而不是name

例如$service->user->id$service->user->email