使用Laravel访问多对多关系

时间:2018-05-10 09:39:00

标签: php laravel octobercms

所以我遇到的问题是访问和使用多对多关系中的数据,我在10月份使用Laravel cms。

我使用pivot table使用owner_id and manytomany_id拥有Owners和ManyToMany对象。我可以使用下面的代码访问OneToMany relationship,但尝试访问ManyToMany objects我无法分配它们,这是我正在使用的代码,

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

我的关系都被定义为

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'
    ]
];

如果我定义了一个页面变量,例如$this->something,它将不允许我分配ManyToMany查询的结果,但如果我将结果分配给$ something,我可以记录结果并查看返回数据,为什么我不能访问它?

我不急于加载这些结果的原因是需要限制项目数量,经过大量研究后我发现无法通过热切加载完成。

这是我收到的错误:

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

如果有人能对此有所了解,那将会有很多帮助!

1 个答案:

答案 0 :(得分:0)

在doc:https://laravel.com/docs/5.3/eloquent-relationships#many-to-many中说关系有一个数据透视表,在这个表中有一些列引用表来形成多种关系。

例如在迁移文件上:

Schema::create('category_product', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('category_id');
    $table->integer('product_id');
});;

在产品型号中:

public function extraCategories()
{
    return $this->belongsToMany(Category::class);
}

在分类模型中:

public function extraProducts()
{
    return $this->belongsToMany('App\Product');
}

模型上的其他例子:

public function associacion()
{
    return $this->belongsToMany('App\Product', 'product_related', 'product2_id', 'product_id');
}

在这种情况下,有一个特定的表,第一列和第二列,Eloquent不会与数据透视表和其他模型自动连接。

当您使用修补程序获取数据时,您可以看到:

App\Product {#892
     id: "4555",
     name: "PRODUCT NAME",
     extraCategories: Illuminate\Database\Eloquent\Collection {#912
       all: [
         App\Category {#907
           id: "245",
           description: "YYYYY",
           pivot: Illuminate\Database\Eloquent\Relations\Pivot {#902
             product_id: "4555",
             category_id: "245",
           },
         },
         App\Category {#908
           id: "135",
           description: "XXXXX",
           pivot: Illuminate\Database\Eloquent\Relations\Pivot {#901
             product_id: "4555",
             category_id: "135",
           },
         },
       ],
     },
   }

在这种情况下,在集合数组中返回多个与多个关系的extraCategories。

我希望这能解决你的问题。