Yograj Gupta
Yograj Gupta

Reputation: 9869

Laravel and jenssegers mongodb relationship data not saving

I have 2 classes in Laravel

class Company
{
  public function people()
  {
     return $this->hasMany('Person');
  }
}

class Person 
{
  public function company()
  {
    return $this->belongsTo('Company');
  }
}

Now in another class, I am creating a person object and setting company_id with a defined variable $companyId.

$person = new Person;
$person->company_id = $companyId; //Code not executing after it.
$person->save();

When I am setting $companyId in $person, it is just being in recursive call and never come back.

I have also tried this code as well, but no luck, again, it is stuck somewhere and never save.

$company = Company::find($companyId);
$person = new Person;
$company->people()->save($person); // Never execute this

Please provide some sight, what wrong I am doing, I googled for this but not found which resolve this.

This app was created and maintain in laravel 4.2 and there it is working fine, but while upgrading this to laravel 5.7, this is giving issue here.

Thanks

Upvotes: 0

Views: 387

Answers (1)

Jigar
Jigar

Reputation: 3261

can you try below code may be it will work for you.

Please add a relationship like this in your code.

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

class Person 
{
  public function company()
  {
    return $this->belongsTo('App\Company');
  }
}

And try to save Person object like this here I don't know fields of person table so for a demo, I have used a name, so replace it as per your requirements.

$comment = new App\Person(['name' => 'test']);

$company= App\Company::find(1);

$company->people()->save($person);

Upvotes: 1

Related Questions