从Laravel 5.2中的Eloquent模型中检索后的变量类型更改

时间:2016-03-26 14:57:15

标签: php eloquent laravel-5.2

我在数据库中有一个名为marital_status的表。它只包含两列user_id(类型为Integer),另一列名为is_married(类型为boolean)。

因此,当我通过雄辩模型检索用户的婚姻状况时,我会除了布尔值。

public class register extends AppCompatActivity {

EditText username, password;
Button registartion;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
}

private Connection getConnection()
{

    String host = "jdbc:mysql://jdbc.fmc.me.uk:3306/db_ben";
    String u = "user_ben";
    String p = "******";
    try
    {
        Connection con = DriverManager.getConnection(host, u, p);
        return con;
    } catch (SQLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

private boolean registerUser(){

    //Get username
    EditText regUsernameBox = (EditText) findViewById(R.id.RegUsername);
    String regUsernameStr = regUsernameBox.getText().toString();

    //Get password
    EditText regPasswordBox = (EditText) findViewById(R.id.RegPassword);
    String regPasswordStr = regPasswordBox.getText().toString();

    System.out.println(regUsernameStr);
    System.out.println(regPasswordStr);

    int i = 0;
    Connection con = getConnection();
    try {
        PreparedStatement pst = con.prepareStatement("insert into users values(?,?)");
        pst.setString(1, regUsernameStr);
        pst.setString(2,regPasswordStr);
        i = pst.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    if(i>0)
        return true;
    return false;
}

public void buttonClick() {
    final Button registerUsers = (Button) findViewById(R.id.bRegister);

    registerUsers.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            registerUser();
        }
    });
}
}

结果是正确的,但我没有使用布尔字符串' 0'或者' 1'。有人可以解释一下吗?

1 个答案:

答案 0 :(得分:1)

您可以在模型中解决此问题:

protected $casts = [
    'is_married' => 'boolean'
];

https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting