简体   繁体   中英

Laravel hasMany relationship issue

I have a problem about table relationship in models. when I try to add hasMany relation there is an error popping up.

Call to undefined relationship [Plan100] on model [App\\AllPlan].

This is the main table model places

protected $table = "places";

public $with = ["AllPlan"];

public function allplans()
{
    return $this->hasMany("App\AllPlan");
}

And AllPlan table model

protected $table = "all_plans";

public function place()
{
    return $this->belongsTo("App\Place");
}

No problem 'till here. I can see the AllPlan data inside the Places table on json response... But, the problem is popping up when I try to add hasMany relation into AllPlan table like below.

Now AllPlan table model looks like this.

protected $table = "all_plans";

 public $with = [
     "Plan100",
     "Plan90",
];

public function place()
{
    return $this->belongsTo("App\Place");
}

public function plan()
{
    return $this->hasMany(
        "App\Plan100",
        "App\Plan90"
    );
}

And the Plan100 table model look like this:

public function plan()
{
    return $this->belongsTo("App\AllPlan");
}

But it's giving me an error. But I am not very sure where do I do wrong. Thank you.

Seems to me that you are trying to create two new relations, but this can't be done inside one function. Create two functions and refactor your code like this:

public function plan100()
{
    return $this->hasMany(App\Plan100", 'foreign_key');
}

public function plan90()
{
    return $this->hasMany(App\Plan90", 'foreign_key');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM