【发布时间】:2016-05-24 06:44:17
【问题描述】:
我有这个 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,如果没有,则添加来自请求的数据的新行,但如果 excist 行具有相同的 start然后检查price 的值,如果price 高于当前更新该行...
请帮助我在 offercontroller 的 store 函数中编写该查询...
【问题讨论】:
-
如果你能解释一下if存在的条件,我可以修改下面的答案。
-
所以首先我添加报价,然后我检查 maxoffer 表是否存在具有相同 article_id 的行并开始,如果不是我添加新行,但如果行存在,那么我需要检查新价格是否高于当前,如果是,我需要更新该行完成(使用新数据)...
-
如果存在 - 如果已经有具有相同 START 和 ARTICLE_ID 值的行(然后检查价格) - 如果不存在,则在 mysql 数据库表中添加新行
-
检查更新的答案。
标签: mysql laravel model controller eloquent