【问题标题】:Laravel one to many relationship resultsLaravel 一对多关系结果
【发布时间】:2017-03-27 06:50:38
【问题描述】:

您好,我正在尝试创建一对多关系。用户表中的一个用户可以拥有多个公司,而另一侧的公司可能只有一个用户。

我对公司表的迁移是

  public function up()
    {
        Schema::create('companies', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('address');
            $table->string('city');
            $table->string('state');
            $table->string('contact_person');
            $table->string('phone');
            $table->string('industry');
            $table->string('website');
            $table->integer('id_user')->unsigned();
            $table->foreign('id_user')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
        });
    }

我的用户模型是

  /**
     * Get the posts for the user.
     */
    public function companies()
    {
        return $this->hasOne('App\Company','user_id');
    }

我的公司模式是

   public function users()
    {
        return $this->belongsTo('App\User','id');
    }

我正在尝试为特定用户获取所有公司

尝试 whereHas 但关系对象中没有数据

      $results = Company::whereHas('users', function ($query) {
         $query->where('users.id',1);
       })->get();

我的错误在哪里?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您应该更改的第一件事是companies() 关系。必须是hasMany,而不是hasOne

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

    然后用他所有的公司获取用户:

    $result = User::where('id', $id)->with('companies')->first();
    

    或者,如果您想在示例中使用 Company 模型并仅获取公司:

    $result = Company::where('user_id', $id)->get();
    

    另外,您在迁移中使用id_user。将其更改为user_id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 2018-01-11
      • 2018-06-15
      • 2018-09-27
      • 2017-12-24
      • 2018-04-20
      相关资源
      最近更新 更多