存储offer(),其中包含user_id和article_id - laravel

时间:2015-12-19 11:58:25

标签: php laravel model controller store

我创建了一个包含用户,文章和优惠的简单应用。现在,用户可以为该文章创建文章和优惠。 SO用户有很多文章和许多优惠,文章belogsTo用户和hasMany优惠和提供belongsTo用户和文章...所以我写道:

在用户模型:

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

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

文章模型:

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

    public function offer(){

        return $this->hasMany('App\Offer');
    }

并在Offer模型中写道:

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

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

但是现在我有一个探针如何在我的OffersController中创建store()函数 - 我试试:

public function store(Requests\OfferRequest $request)
    {
        $offer = new Offer($request->all());

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

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

        return redirect('offers');
    }

但我收到错误:

  

Builder.php第2071行中的BadMethodCallException:调用undefined   方法Illuminate \ Database \ Query \ Builder :: article()   enter image description here

我的表格代码是:

{!! Form::open(['url'=>'offers']) !!}
        <div class="form-group">
            {!! Form::label('price','Price') !!}
            {!! Form::text('price', null, ['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::submit('Add Offer',  ['class'=>'btn btn-primary form-control']) !!}
        </div>
        {!! Form::close() !!}

我的路线是:

Route::resource('offers', 'OffersController');

如何添加Offer和该优惠需要具有Auth :: user和article_id的user_id ...

当我使用:Auth::user()->offer()->save($offer);然后存储优惠,但只有ith user_id,我不知道如何将article_id存储为优惠。

另外我知道我可以将{{$article->id}}放在刀片模板上并从表单中获取它们但是它存在安全风险......

还有一件事 - 只是用户(管理员)可以创建文章,但所有用户都可以为文章提供优惠,因此我需要在优惠表中提供user_id ...

请帮忙!

1 个答案:

答案 0 :(得分:2)

我认为问题在于您没有选择附加要约的文章。 尝试选择文章或直接将其保存在用户身上。

在您的控制器中,您可以执行以下操作以将要约保存到特定文章...

Auth::user()->articles()->find($articleID)->offer()->save($offer);

或像这样保存给用户......

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

不确定您如何在文章和用户之间分享优惠,但如果您愿意则很酷。

希望有帮助...

快速小建议:使提供方法多元化,因为它是一个hasMany关系。