Thursday, May 10, 2018

Accessing Many to Many Relationships with Laravel - development

Accessing Many to Many Relationships with Laravel

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' => [
        'KaiRelationsModelsManyToMany', 
        'table' => 'kai_relations_owner_many_to_many'
    ]
];
public $belongsToMany = [
    'owner' => [
        'KaiRelationsModelsOwner', 
        '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!



from Laravel Questions and Answers https://laravelquestions.com/php/accessing-many-to-many-relationships-with-laravel/
via Lzo Media

No comments:

Post a Comment