Laravel的Model :: create()函数没有设置自定义字段值

Jac*_*ack 3 php laravel eloquent laravel-5

Laravel新手在这里,对不起,如果这很痛苦,但我已经坚持了很久!

目的:为了质量分配一个Quote::create()数据库插入与来自形成全值,加上用户ID设置为在用户当前登录.

问题:user_id列永远不会写入数据库.每隔一列,但user_id保持为0.

我当然尝试添加user_id到$fillable数组中,但我不希望它是用户可填充的 - 我希望它由Laravel的Auth::id()函数设置.

任何想法为什么不会存储?是因为该$quote->create()函数不考虑先前设置的数据,只是将其参数作为要保存的所有内容?如果是这样,我该怎么做?

这是我的控制器的store()功能:

/**
     * Stores a created quote in the database
     *
     * @param QuoteRequest $request
     *
     */
    public function store(QuoteRequest $request)
    {
        // This method will only get fired if QuoteRequest passes
        $quote = new Quote;
        $quote->user_id = Auth::id();
        $quote->create($request->all());

        echo 'Job done';
    }
Run Code Online (Sandbox Code Playgroud)

这是我的Quote模特:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;

class Quote extends Model {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'quotes';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'quote_person',
        'quote_value',
        'quote_date'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [ ];

    /*
     * Request/User many-to-one relationship
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /*
     * Belongs to current User scope
     */
    public function scopeMine($query)
    {
        return $query->where('user_id', Auth::id());
    }

}
Run Code Online (Sandbox Code Playgroud)

Paw*_*zad 7

试试这个,看它是否有效.

public function store(QuoteRequest $request)
{
    // This method will only get fired if QuoteRequest passes
    $quote = new Quote;
    $quote->fill($request->all());
    $quote->user_id = Auth::id();
    $quote->save();

    echo 'Job done';
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您在用户模型上建立了关系,则可以在一行中完成所有操作:Auth :: user()-&gt; quotes()-&gt; create($ request-&gt; all());`更好的是,您可以摆脱Auth外观,并从请求中获取用户:$ request-&gt; user()-&gt; quotes()-&gt; create($ request-&gt; all());。 (2认同)