Laravel模型奇怪的行为

时间:2018-02-17 06:48:44

标签: laravel model eloquent

好奇为什么。

 public function get_number() {

    if(Model::get()->isEmpty()) {

        $number = Model::create(['number' => '1111111111']);

        $nubmer = $number->number; //(returns a... model, that's a suprise for me)

    } else {

        $number = Model::orderBy('number', 'desc')->first()->number;

        $number = Model::create(['number' => $number+1]);

        $number = $number->number; //(returns a property 1111111112 etc).

    }

return $number;

在这两种情况下,我都试图获得模型的属性:

$number = $number->number;

但是当“If”部分有效时,它返回一个模型(不是属性)...... 当“else”部分工作时,它返回一个属性(我所期望的)。

这意味着我对Laravel中的某些内容并不了解:)

为什么它会在“If”情况下返回一个完整的模型?:)

1 个答案:

答案 0 :(得分:2)

您的if阻止包含拼写错误:

public function get_number() {

if(Model::get()->isEmpty()) {

    $number = Model::create(['number' => '1111111111']);

    // this should be $number
    // $nubmer = $number->number;
    // change it to
    $number = $number->number;

} else {

    $number = Model::orderBy('number', 'desc')->first()->number;

    $number = Model::create(['number' => $number+1]);

    $number = $number->number; //(returns a property 1111111112 etc).

}

您也不需要分配$number = $number->number;,只需返回:

return $number->number;

示例:

public function get_number() {
    if(Model::get()->isEmpty()) {
        $number = Model::create(['number' => '1111111111']);
    } else {
        $number = Model::orderBy('number', 'desc')->first()->number;
        $number = Model::create(['number' => $number+1]);
    }

    return $number->number;
}