ShaneMit ShaneMit - 1 month ago 8
PHP Question

Laravel ManyToMany null id in where clause

I am having this same issue. Exactly the same issue accept different class and table names. Does anybody have some insight?

Site:
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function categoryBlocks()
{
return $this->belongsToMany(Category::class, 'blocked_category');
}

Category:
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function sites()
{
return $this->belongsToMany(Site::class, 'blocked_category');
}


The query properly generates when querying from category to site but not from site to category. (I have tried renaming the method on the site Model but it doesn't help at all.)

$catBlocks = $category->sites()->get(); // Query creates a category_id value in the query
$blocks = $site->categoryBlocks()->get(); // Query doesn't create a site_id value in the query


Table: blocked_category
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`site_id` int(10) unsigned NOT NULL,
`category_id` int(10) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,


Table: sites
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`publisher_id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`status_id` int(11) NOT NULL DEFAULT '1',


Table: categories
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

Answer

So I found the issue. The instance of the object being used to query wasn't being fully hydrated which was causing the query builder not to see the relationship properly.

I was getting the instance of the object passed into the method, but for some reason it wasn't a fully hydrated instance, so I just had to manually hydrate the Site object before running the query.

Comments