【问题标题】:Laravel one to many relationship issueLaravel 一对多关系问题
【发布时间】:2019-11-25 07:39:48
【问题描述】:

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

我有两个表,一个是提供一些服务和其他表服务的用户。我想在它们之间建立一对多的关系。 因为用户必须有许多服务。 for service 必须属于 To on 用户。 我的代码:

用户.php

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

服务.php

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

控制器.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.服务

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)

【问题讨论】:

  • “我有一些问题” - 那么究竟是什么问题?你有任何错误吗?
  • 是的,但我按照以下答案修复了它。谢谢。

标签: laravel laravel-5 eloquent


【解决方案1】:

替换

{{$service-&gt;user_id[0]??'not'}}

{{$service-&gt;user ? $service-&gt;user-&gt;name : 'not'}}

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

喜欢$service-&gt;user-&gt;id$service-&gt;user-&gt;email

【讨论】:

  • 很高兴听到它奏效了。您可以接受并投票赞成答案;)
猜你喜欢
  • 2014-11-11
  • 2014-02-17
  • 2021-11-15
  • 2015-09-14
  • 2019-05-06
  • 2014-05-24
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
相关资源
最近更新 更多