简体   繁体   English

在 Laravel 5.2 中使用 eloquent 而不是查询

[英]Use eloquent instead of query in Laravel 5.2

I made a query, but I'm not satisfied, because I wanted to do it with Eloquent!我提出了一个查询,但我不满意,因为我想用 Eloquent 来做!

Here is the query:这是查询:

Tournament::leftJoin('category_tournament', 'category_tournament.tournament_id', '=', 'tournament.id')
        ->leftJoin('category_tournament_user', 'category_tournament_user.category_tournament_id', '=', 'category_tournament.id' )
        ->where('category_tournament_user.user_id', '=',$this->id )
        ->select('tournament.*')
        ->distinct()
        ->get();

Migrations:迁移:

Schema::create('tournaments', function(Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('categories', function(Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('category_tournament', function(Blueprint $table) {
    $table->increments('id');
    $table->integer('category_id');
    $table->integer('tournament_id');
    $table->timestamps();

    $table->foreign('tournament_id')
            ->references('id')
            ->on('tournament')
            ->onDelete('cascade');

        $table->foreign('category_id')
            ->references('id')
            ->on('category')
            ->onDelete('cascade');
});

Schema::create('category_tournament_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_tournament_id')->unsigned()->index();
        $table->foreign('category_tournament_id')
            ->references('id')
            ->on('category_tournament')
            ->onDelete('cascade');


        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

        $table->unique(array('category_tournament_id', 'user_id'));

        $table->boolean('confirmed');

        $table->timestamps();
        $table->softDeletes();
        $table->engine = 'InnoDB';


    });

Models楷模

class Tournament extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function categoryTournaments()
    {
        return $this->hasMany(CategoryTournament::class);
    }
}

class Category extends Model
{
    public function tournaments()
    {
        return $this->belongsToMany(Tournament::class);
    }

    public function categoryTournament()
    {
        return $this->hasMany(CategoryTournament::class);
    }
}

class CategoryTournament extends Model
{
    protected $table = 'category_tournament';

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function tournament()
    {
        return $this->belongsTo(Tournament::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'category_tournament_user');
    }
}

class User extends Authenticatable
{
    public function categoryTournaments()
    {
        return $this->belongsToMany(CategoryTournament::class, 'category_tournament_user');
    }
}

The query works, I just want to know how should I do it with Eloquent because I was not able to do it by myself :(查询有效,我只是想知道我应该如何使用 Eloquent 来完成它,因为我无法自己完成 :(

Any idea how to do it???知道怎么做吗???

First of all you have to add foreign keys to your migrations Table + it's useful to make them unsigned since you will probably never have any negative ids:首先,您必须在迁移表中添加外键 + 使它们未签名很有用,因为您可能永远不会有任何负 id:

$table->integer('tournament_id')->unsigned();
$table->foreign('tournament_id')->references('id')->on('tournaments');

Since you already have the relations for your Model you should be able to use eloquent to get the contents.由于您已经拥有模型的关系,因此您应该能够使用 eloquent 来获取内容。

You can stick to this page for further information on Eloquent: https://laravel.com/docs/5.0/eloquent您可以访问此页面以获取有关 Eloquent 的更多信息: https : //laravel.com/docs/5.0/eloquent

Should be something like this:应该是这样的:

$tournaments = Tournament::with('category_tournament')
   ->with('category_tournament_user')    
   ->where('category_tournament_user.user_id', '=',$this->id ) 
   ->distinct()
   ->get();

You can use the contents of $tournaments afterwards:之后您可以使用 $tournaments 的内容:

$tournaments->category_tournament->name;

Hope I didn't miss any crucial step, but I think it should be working by doing these changes.希望我没有错过任何关键步骤,但我认为通过进行这些更改应该可以发挥作用。

Edit:编辑:

https://laravel.com/docs/5.1/eloquent-relationships#eager-loading https://laravel.com/docs/5.1/eloquent-relationships#eager-loading

When accessing Eloquent relationships as properties, the relationship data is "lazy loaded".当访问 Eloquent 关系作为属性时,关系数据是“延迟加载”的。 This means the relationship data is not actually loaded until you first access the property.这意味着在您第一次访问该属性之前不会实际加载关系数据。 However, Eloquent can "eager load" relationships at the time you query the parent model.但是,Eloquent 可以在您查询父模型时“急切加载”关系。 Eager loading alleviates the N + 1 query problem. Eager loading 缓解了 N+1 查询问题。 To illustrate the N + 1 query problem, consider a Book model that is related to Author:为了说明 N+1 查询问题,考虑一个与 Author 相关的 Book 模型:

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

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