在控制器

时间:2016-02-12 23:41:29

标签: mysql laravel model controller eloquent

我有OFFERS的这个迁移表:

public function up()
    {
        Schema::create('offers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('article_id')->unsigned();
            $table->integer('price');
            $table->string('comment');
            $table->timestamps();
            $table->string('key');
            $table->string('title');
            $table->timestamp('start');

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

            $table->foreign('article_id')
                ->references('id')
                ->on('articles')
                ->onDelete('cascade');
        });
    }

此外,模特我也有:

class Offer extends Model
{
    //
    protected $fillable = [
        'price',
        'comment',
        'article_id',
        'key',
        'start'
    ];

    protected $dates = [
        'start'
    ];

    public function setStartAttribute($date){
        $this->attributes['start']= Carbon::createFromFormat('m/d/Y h:i a', $date);
    }
    public function getStartAttribute($date){
        return (new Carbon($date))->toRfc2822String();
    }

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

    public function article(){
        return $this->belongsTo('App\Article');
    }
}

现在在控制器我只有存储功能:

public function store(Requests\OfferRequest $request)
    {

            $offer = new Offer($request->all());

            Auth::user()->offer()->save($offer);

            Alert::success('Offer is succesfully added!', 'Good job!')->persistent("Close");

        return Redirect::back();

    }

现在我也有相同型号的MAXOFFER。同样是迁移和模型。

我想要做的是在OffersController存储方法中添加一个查询,该查询会在maxoffers表中执行start,如果没有,则添加包含来自请求的数据的新行,但是如果excist行具有相同的{ {1}}值然后检查start以及price是否高于当前更新该行...

请帮我在offercontroller中的商店功能内进行查询...

1 个答案:

答案 0 :(得分:1)

通过猜测maxoffer模型中的关系Maxoffer来创建以下查询。

$maxoffer = Auth::user()->maxoffer()
                        ->where('address_id', $request->input('address_id'))
                        ->where('start', $request->input('start'))->first();

   if($maxoffer==null)
    {
      Ath::user()->maxoffer()->create($request->all());
    }
    else
    {
      if($maxoffer->price < $request->input('price'))
      {
         $newOffer = Auth::user()->maxoffer()
                    ->where('address_id', $request->input('address_id'))
                    ->where('start', $request->input('start'))
                                     ->update(['price'=>$request->input('price')]);
      }
    }