【问题标题】:call custom model's method from controller in laravel4从 laravel 4 中的控制器调用自定义模型方法
【发布时间】:2023-04-05 07:31:01
【问题描述】:

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

<?php

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

    public static $rules = array();

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

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

【问题讨论】:

    标签: php function model controller laravel


    【解决方案1】:

    你也可以这样做,使用

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

    从控制器调用

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

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

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

    并从控制器调用它

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

    同时检查this answer

    【讨论】:

    • 感谢您的快速回复。除了使用静态关键字还有其他方法吗
    • 欢迎@SannySinghs!检查第二个例子,它没有使用static关键字,而是使用Scope
    【解决方案2】:

    有人这样回答我。

    在 SessionsController 中添加以下内容

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

    【讨论】:

    • 你检查了我的第二个例子,没有static关键字,可以使用你的方法,但为什么不使用Laravel样式语法,这也很容易使用,Class::mentodName()即使它不是静态的.
    猜你喜欢
    • 2013-06-02
    • 2023-03-03
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2014-08-06
    相关资源
    最近更新 更多