Ad

Accessing Many To Many Relationships With Laravel

- 1 answer

So the issue I am having is accessing and using data from a many to many relationships, I am using Laravel in October cms.

I have Owners and ManyToMany objects with a pivot table using owner_id and manytomany_id. I can access OneToMany relationship just fine using the code below, but trying to access ManyToMany objects I cant assign them, this is the code I'm using,

    foreach ($this->owners as $owner) {
        $owner['onetomany'] = $owner->onetomany()->take($this->maxJobs)->get();
        $owner['manytomany'] = $owner->manytomany()->take($this->maxTeam)->get();    
    }

my relationships are both defined as so

public $belongsToMany = [
    'manytomany' => [
        'Kai\Relations\Models\ManyToMany', 
        'table' => 'kai_relations_owner_many_to_many'
    ]
];
public $belongsToMany = [
    'owner' => [
        'Kai\Relations\Models\Owner', 
        'table' => 'kai_relations_owner_many_to_many'
    ]
];

if I define a page variable such as $this->something, it will not allow me to assign the results of the ManyToMany query, but if I assign the results to just $something, I can Log the results and see the returned data, so why can't I access it?

The reason I'm not Eager loading these results is the need to limit the number of items, which after much research I found could not be done with eager loading.

This is the error i receive:

SQLSTATE[HY000]: General error: 2031 (SQL: select * from `kai_relations_many_to_manies` where `id` in (?))

If anyone can shed any light on this it would be a lot of help!

Ad

Answer

foreach ($this->owners as $owner) {
        $owner['onetomany'] = $owner->onetomany()->take($this->maxJobs)->get();
        $owner['manytomany'] = $owner->manytomany()->take($this->maxTeam)->get();    
    }

I think This is not working because you have defined relationship already with name manytomany So it will try to override your manytomany with data you are trying to retrieve with $owner->manytomany()->take($this->maxTeam)->get();

Now you can change the name from $owner['manytomany'] to something different than your relationship name i.e $owner['ownerManyToMany'] and then may be you can get your data.

Try this

foreach ($this->owners as $owner) {
        $owner['onetomany'] = $owner->onetomany()->take($this->maxJobs)->get();
        $owner['ownerManyToMany'] = $owner->manytomany()->take($this->maxTeam)->get();    
    }
Ad
source: stackoverflow.com
Ad