duancilan5124 2015-09-16 14:56
浏览 383
已采纳

在Laravel 5中调用模型中的方法

I've created a model called Hangman. Inside a controller I'm inserting a row in the database like this

$hangman = new Hangman();
$hangman->word = 'exampleWord';
$hangman->lives = 3;
$hangman->save();

So far so good.

I've got two questions:

1) Is it best practice to keep inserting things in the controller?

I assume NO, so I created this method in the model, which I think would be cleaner to call from the controller

public function insert($word, $lives)
{
    $hangman = new Hangman();
    $hangman->word = $word;
    $hangman->lives = $lives;
    $hangman->save();

    return $hangman;
}

So, my real question (assuming question 1 is NO) is:

2) How would I call this method from the controller?

This doesn't work

 \App\Hangman::insert('exampleword', 4);

Namespaces are correct.

I know it's very basic, thanks guys

  • 写回答

2条回答 默认 最新

  • dongmoxin7111 2015-09-16 15:06
    关注

    Nobody can answer your first question properly, as it's a matter of personal preference and people have various opinions. Putting it in the model may be a good idea, as might putting it in a repository. In the right application, having it in a controller might be worth it, whereas other systems may favour yet other solutions.

    As for your second question: since you're in the Hangman model, you should make the self-referential call static, and also the method itself.

    public static function insert($word, $lives)
    {
        $hangman = new static;
        $hangman->word = $word;
        $hangman->lives = $lives;
        $hangman->save();
    
        return $hangman;
    }
    

    And that should be enough. You could also save yourself a few lines:

    public static function insert($word, $lives)
    {
        return static::create(compact('word', 'lives'));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法
  • ¥15 dnat基础问题,本机发出,别人返回的包,不能命中