我有2个表:'users'和'nests'以及1个数据透视表:'nest_user'。在我的数据透视表中,我有我要过滤的电子邮件地址,因此我可以抓取所有具有相关电子邮件地址的嵌套。这是我的情绪:
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username');
$table->text('bio');
$table->string('picture');
$table->string('email');
$table->string('password');
$table->integer('visits');
$table->integer('nest_id');
$table->timestamps();
});
}
public function up()
{
Schema::create('nests', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('info');
$table->integer('note_id');
$table->integer('website_id');
$table->integer('image_id');
$table->integer('video_id');
$table->integer('location_id');
$table->integer('user_id');
$table->integer('share_id');
$table->string('inviteAuth');
$table->string('tid');
$table->timestamps();
});
}
public function up()
{
Schema::create('nest_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id');
$table->integer('nest_id');
$table->string('inviteEmail');
$table->timestamps();
});
}
我可以根据用户ID这样做没问题:
Route::get('/t1', function () {
$nest = User::find(2)->nest()->where('inviteEmail', '=', 'martinelli@gmail.com')->get();
foreach( $nest as $nest)
echo $nest->name, ': ', $nest->pivot->inviteEmail, "</br>";
});
我可以在枢轴中获取巢和名称以及电子邮件 - 真棒......但是,我想找到所有“巢”,其中包含与用户ID无关的关联电子邮件。这让我更接近但仍然无法正常工作:
Route::get('/t4', function () {
$users = User::all();
foreach($users as $users)
{
$nests = $users->with(array('nest' => function($query) {
$query->where('inviteEmail', '=', 'martinelli@gmail.com');
}))->get();
foreach($nests->nest as $nest)
{
echo $nest->name,"<br />";
}
}
});
我收到此错误:
Undefined property: Illuminate\Database\Eloquent\Collection::$nest
答案 0 :(得分:0)
我不确定我是否完全理解你的问题,但你的最后一个代码块没有意义。您需要在获取用户时执行此操作。此外,你得到的错误是有道理的,因为$ nests(Collection)没有$ nest属性。
同样,我不确定这是你所追求的,但试一试:
Route::get('/t4', function () {
// Get all users and their nests where nests are filtered by inviteEmail
$users = User::with(array('nest' => function($query) {
$query->where('inviteEmail', '=', 'martinelli@gmail.com');
}))->get();
// Loop through all users
foreach($users as $user)
{
// I'm asuming you defined the relation as nests() in your User model.
foreach($user->nests as $nest)
{
echo $nest->name . "<br />";
}
}
});