2

example:

$example = new Model();
$example->name = 'abc';
$example->save();

How can I judge the results of ORM? Like this?

if($example->save){
    ...//do someting
}else{
    ...//do someting
}

But,I think it's wrong.Because,$example->save() will return an object。So,theelse{} can't run forever.How can I judge the results of ORM?

Thanks for everyone.

SoulKeep
  • 35
  • 3

2 Answers2

1

save() will return a boolean. So you can either do:

$saved = $example->save();

if(!$saved){
    // something
}

Or directly save in the if:

if(!$example->save()){
    // something
}
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53
0

You can use insert() method which returns true or false:

$inserted = Model::insert(['name' => 'abc']);
    ...//do someting
if($inserted){

}else{
    ...//do someting else
}

Or, you could use try... catch clause:

    try
    {
        Model::insert(['name' => 'abc']);

        ...//do someting
    }
    catch(\Exception $e)
    {
        ...//do someting else
    }

You can try to do this:

$example = new Model();
$example->name = 'abc';
$example->save();
if ($example) { ... }

But it's not safe, because you can get error in this part and you'll not be able to catch it:

$example->name = 'abc';
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279