laravel 从laravel4中的控制器调用自定义模型的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20395169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:44:12  来源:igfitidea点击:

call custom model's method from controller in laravel4

phpfunctionmodelcontrollerlaravel

提问by Sanny Singhs

I am trying to call a custom method in my Emailmodel from my SessionsController. This is my model

我正在尝试Email从我的模型中调用自定义方法SessionsController。这是我的模型

<?php

class Email extends Eloquent {
    protected $guarded = array();

    public static $rules = array();

    public function sendMail($type,$data)
    {
        echo "yes";
    }
}

From my SessionsControllerI wanna call sendMailmethod. How am I supposed to call it?

从我的SessionsController我想调用sendMail方法。我该怎么称呼它?

回答by The Alpha

You can do it either, using

你也可以这样做,使用

class Email extends Eloquent {
    public static function sendMail($type, $data)
    {
        //...
    }
}

And call from controller

并从控制器调用

Email::sendMail('someType', $dataArray);

Or, you can use Scope(instead of static)

或者,您可以使用Scope(而不是static)

class Email extends Eloquent {
    public function scopeSendMail($query, $type, $data)
    {
        // You can use $query here
        // i.e. $query->find(1);
    }
}

And call it from controller

并从控制器调用它

Email::sendMail('someType', $dataArray);

Also check this answer.

还要检查这个答案

回答by Sanny Singhs

someone answer me like this .

add following in SessionsController

有人这样回答我。

在 SessionsController 中添加以下内容

$type = ...
$data = ...

$email = new Email;
$email->sendMail($type,$data);