php - Laravel 的 Model::create() 函数未设置自定义字段值

标签 php laravel eloquent laravel-5

Laravel 新手,抱歉,如果这很明显,但我已经坚持了很长时间!

目标:要使用表单中的完整值批量分配 Quote::create() 数据库插入,设置当前登录用户的用户 ID。

问题:user_id 列从未写入数据库。每隔一列,但 user_id 保持为 0。

我当然尝试过将 user_id 添加到 $fillable 数组,但我不希望它是用户可填写的 - 我希望它由Laravel 的 Auth::id() 函数。

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

这是我的 Controller 的 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';
    }

这是我的 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());
    }

}

最佳答案

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

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';
}

关于php - Laravel 的 Model::create() 函数未设置自定义字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30198565/

相关文章:

javascript - 从输入到文本区域自动输入并将文本换行到文本区域?

php - 分页链接

php - 检查行是否存在以及是否没有插入数据

mysql - Laravel:试图获得非对象的属性

php - 通过 AJAX 将数据从 localStorage 发送到 PHP 并将其保存在 HTML 文件中

php - 用jQuery替换OnPage Text,然后提示文件下载

PHP 认证库

laravel - 如何在 Laravel 5.8 中安装我的包? "Your requirements could not be resolved to an installable set of packages."

php - laravel 中 yajra 数据表的问题

mysql - Eloquent : relationship from relationship