Laravel是一对多的关系结果


Laravel one to many relationship results

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

我对公司表的迁移是

  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');
    }

我正试图获得所有公司的特定用户

在关系对象

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

我的错误在哪里?

首先要更改的是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