Laravel 5将字符串主键作为整数返回

时间:2016-06-10 11:51:23

标签: laravel eloquent laravel-5.2

我的数据库中有一个设置表,如下所示:

|    name    |    value    | validation |
|  site-name | Sample Site |   max:255  |
| site-title | Sample Site |   max:255  |

这就是我的设置模型的样子:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $primaryKey = 'name';
    protected $fillable = ['name', 'value'];
}

以及用于在所有视图中共享设置变量的Controller.php文件:

<?php

namespace App\Http\Controllers;

use App\Setting;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;

class Controller extends BaseController
{
    use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;

    protected $usr;
    protected $settings;

    public function __construct()
    {
        $this->usr = Auth::user();
        view()->share('usr', $this->usr);

        $this->settings = array();
        $allSettings = Setting::all();

        foreach ($allSettings as $setting)
            $this->settings[$setting->name] = $setting->value;

        print_r($this->settings);

        view()->share('settings', $this->settings);
    }
}

print_r用于调试。 出于某种原因,print_r输出:

  

数组([0] =&gt;示例网站)   代替:   数组([site_name] =&gt;示例网站)

看起来$ setting-&gt; name返回一个整数而不是一个字符串(数据库中的name列设置为varchar)。

任何想法为什么会发生?

2 个答案:

答案 0 :(得分:6)

如果模型中没有整数使用

public $incrementing = false;

答案 1 :(得分:-1)

好的,我知道了。

我需要做的就是将这一行添加到我的设置模型中:

public $incrementing = false;