1

我有 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  
4

1 回答 1

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 />";
        }
    }
});
于 2013-06-13T18:49:44.787 回答