php - 如何在 Laravel 中检索与多对多关系链接的模型?

标签 php mysql database laravel model

我有三个模型:墙、柱和约束。他们都有一个id。

Post
id

Wall
id

Constraint
id

Post_wall
post_id
wall_id
constraint_id

在 Wall 和 Post 之间我有一个 ManyToMany 关系。在该关系的数据透视表中,我有一个列constraint_id。当我检索链接到墙的所有帖子时,我还需要在数据透视表中链接约束。

现在我可以使用 withPivot('constraint_id') 方法获取constraint_id。

return $this->belongsToMany('App\Wall')
       ->withPivot('constraint_id')

但我想要对象,而不是 id。这在 Laravel 中可能吗?

return $this->belongsToMany('App\Wall')
       ->withPivot('constraint_id')
       ->join('constraints', 'post_wall.constraint_id', '=', 'constraint.id');

我也尝试加入约束表,但它不返回对象。

最佳答案

我认为您需要的是“检索中间表列”。有关此的更多信息,您可以在 https://laracasts.com/discuss/channels/eloquent/how-to-access-data-of-a-pivot-table 找到。或https://laravel.com/docs/5.1/eloquent-relationships#many-to-many

关于php - 如何在 Laravel 中检索与多对多关系链接的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41546167/

相关文章:

php - mod_rewrite : Trailing slash on URL with two GET variables

php - 我不明白为什么我会收到此错误

php - Laravel - 根据表单结果更改查询依赖项

php - 使用php向多个用户发送邮件

mysql - 在 Heroku 上部署 MySQL 数据库的 Node.js 应用程序不断崩溃

ruby-on-rails - 从 Ruby on Rails 应用程序中的模型访问数据

sql - 如何将具有公共(public)列 (A, B) 和 (A, C) 的 2 个查询变成只有一个 (A, B, C)?

php - 通过多次编辑更新 Mysql

sql - 让 SQL 使用正确的索引

c# - “Column count doesn' t 第 1 行的匹配值计数”