Laravel ManyToMany在where子句中为null

时间:2016-10-28 20:15:45

标签: php laravel eloquent many-to-many

我遇到this同样的问题。完全相同的问题接受不同的类和表名。有没有人有一些见解?

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');
}

从类别到站点查询时,查询会正确生成,但不会从站点到类别查询。 (我已尝试在网站模型上重命名该方法,但它根本没用。)

$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,

2 个答案:

答案 0 :(得分:2)

尝试将第三个参数传递给category_id'的categoryBlocks关系:

public function categoryBlocks()
{
    return $this->belongsToMany(Category::class, 'blocked_category', 'category_id');
}

或者您在blocked_category表中称为category_id的任何内容。如果这不起作用,请回复您的数据库架构。

答案 1 :(得分:0)

所以我发现了这个问题。用于查询的对象的实例未完全水合,这导致查询构建器无法正确查看关系。

我得到了传递给方法的对象的实例,但由于某种原因,它不是一个完全水合的实例,所以我只需在运行查询之前手动水合Site对象。

相关问题