Rails中的add_index如何使用" unique:true" 2个参数?

时间:2017-06-28 05:08:30

标签: ruby-on-rails database migration

如何将唯一真值应用于2个ID?

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;


use Illuminate\Support\Facades\Storage;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'userimage' => 'required|image'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $path = Storage::putFile('userimages',$data['userimage']);
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'userimage' => $path,
        ]);
    }
}

1 个答案:

答案 0 :(得分:0)

这意味着在table_name中,只有一行的唯一值some_idanother_id具有索引顺序,例如:

id, some_id, another_id
1, 11, 22
2, 11, 33
3, 22, 11

然后数据库将不允许您插入包含some_id = 11another_id = 22的新行

[:some_id, :another_id]的顺序很重要,因为数据库将决定使用基于该顺序的索引,例如:

此查询将使用index:

select * from table_name where some_id = '11'
select * from table_name where some_id = '11' AND another_id = '22'

此查询不会使用index:

select * from table_name where another_id = '22'