简体   繁体   English

Laravel 4数据透视表(很多)-我什么时候使用-> get()和:: with()

[英]Laravel 4 pivot (many to many) table - when do I use ->get() and ::with()

I not getting any results from my many to many relationship when using ->get(). 使用-> get()时,我的多对多关系没有任何结果。 I am testing my relationship with the following: 我正在测试我与以下对象的关系:

The first part works. 第一部分工作。 I am getting all the nests that have test@email.com in the pivot table. 我正在获取所有在数据透视表中包含test@email.com的嵌套。 However I am bringing results back from a specific user ID. 但是,我从特定的用户ID带回结果。 I do not want to do that. 我不想那样做。

Route::get('/test', function () {
  foreach(User::find(2)->nest()->where('inviteEmail', '=', 'test@email.com')->get() as $nest)
    echo $nest->name, ': ', $nest->pivot->inviteEmail, "</br>";
});

I want to get all the nests which are associated to the email. 我想获取所有与电子邮件相关联的巢。 I thought this would work: 我认为这可以工作:

foreach(User::with('nest')->where('inviteEmail', '=', 'test@email.com')->get() as $nest)
  echo $nest->name, ': ', $nest->pivot->inviteEmail, "</br>";
});

But I am getting this: 但是我得到这个:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'inviteEmail' in 'where clause' (SQL: select * from users where inviteEmail = ?) (Bindings: array ( 0 => 'test@email.com', )) SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ inviteEmail”(SQL:从inviteEmail =?的users中选择*)(绑定:数组(0 =>'test@email.com',))

If I drop the ->get() then I get a blank screen. 如果我放下->get()那么我会得到一个空白屏幕。 Any ideas? 有任何想法吗?

To get all nests with email = test@email.com , make use of Eager Loading Constraints. 要使用email = test@email.com获取所有嵌套,请使用“急切加载约束”。 Assuming you do have a Nest class, that's how you should do it: 假设您确实有一个Nest类,那就应该这样做:

$nests = Nest::with(array('user' => function ($query) {
    $query->where('nests_users.email', '=', 'test@email.com');
}));

You can read more on this on the official documentation . 您可以在官方文档中阅读更多内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM