1
votes

Hello i am trying to create one to many relationship. One user from user table could have many companies, on other side company could have only one user.

my migration for company table is

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

my user model is

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

my company model is

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

i am trying to get all companies for specific user

try with whereHas but no data in relation object

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

Where is my error?

1

1 Answers

1
votes

First thing you should change is companies() relation. It has to be hasMany, not hasOne:

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

Then get user with all his companies:

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

Or, if you want to use Company model like in your example and get only companies:

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

Also, you're using id_user in migration. Change it to user_id.