限时抢购Laravel

时间:2019-03-05 14:19:52

标签: php mysql laravel eloquent

首先看一下我的结构代码。我需要为用户汽车提供有限的报价。 我有3硬编码包。注册时免费使用。银和金。如果用户订阅白银,则看到8个报价;如果用户订阅白银,则看到15个报价。如果没有订阅,请参阅2个优惠(免费包装)。我的代码:

用户迁移:

        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();

用户模型:

public function subscriptions_users(){
    return $this->hasMany('App\Subscription');
}
public function cars(){
    return $this->hasMany('App\Car');
}
public function offers(){
    return $this->hasMany('App\Offer');
}

汽车迁移:

 $table->bigIncrements('id');
        $table->string('car_type');
        $table->string('mark');
        $table->string('model');
        $table->unsignedInteger('user_id');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

汽车型号:

public function images() {
    return $this->hasMany(CarImages::class);
}
public function user() {
    return $this->belongsTo('App\User');
}
public function offer() {
    return $this->hasMany('App\Offer');
}

提供迁移:

        $table->increments('id');
        $table->integer('price');
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('car_id');

优惠模式:

public function car() {
    return $this->belongsTo('App\Car');
}
public function user() {
    return $this->belongsTo('App\User');
}

订阅迁移:

        $table->increments('id');
        $table->string('subscription');
        $table->integer('numberOfOffers');

订阅模式:

public function users(){
    return $this->hasMany('App\User');
}

Subscription_user(带有用户和订阅的数据透视表):

        $table->increments('id');
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); //foreign key relation
        $table->integer('subscription_id')->unsigned()->index();
        $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade'); 

Subscription_user模型:

public function users(){
    return $this->belongsToMany('App\User');
}

public function subscriptions() {
    return  $this->belongsToMany('App\Subscription');
}

一切都很好,只是我需要限量版的汽车优惠。受限版本是字段$ table-> integer('numberOfOffers');在订阅表中。我可能与关系有关。.我尝试了此尝试,但没有成功:

public function getOffers($carID) {
$car = Car::find($carID);
$offers = $car->offer()->limit(THIS IS PROBLEM I DON'T KNOW HOT TO CONNECT USER WITH numberOfOffers)->get();
 return response()->json($offers);
}

2 个答案:

答案 0 :(得分:3)

当您需要对关系运行查询时,应使用以下方法:

$offers = Car::where('id', $carId)->with(['offer' => function($query) use ($limit){
    return $query->take($limit);
}])->get();

答案 1 :(得分:0)

尝试一下。

WHERE id = 6