douchensou6969 2015-05-19 08:32
浏览 39

Laravel4.2 - 在模型上共享自定义功能

I have 2 Models ( tables ) on my Laravel4.2 Web Application

Which is : _blog & _text

I'm still learning the process of managing data & logic between Controllers & Models with Laravel

On a my Blog Models, I got a function call listBlog , which is pass a parameter to have a dynamic querying for the _blog table.

But when comes to Text Models, do I need duplicate the listBlog function again to listText ?

It seems repeative for me & what if I got more than 5 tables that wanted to share the function ?

Below are my example codes for Blog Models also Text Models :

Blog :

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Blog extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = '_blog';
    public $timestamp = false;

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */

    public static function listBlog($nextID=0,$status='approved')
    {
        $query = Blog::where('status',$status);
        $query = $query->orderBy('id','desc')->skip($nextID)->take(6);
        return $query->get();
    }
}

Text :

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Text extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = '_text';
    public $timestamp = false;

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */

    public static function listText($nextID=0,$status='approved')
    {
        $query = Text::where('status',$status);
        $query = $query->orderBy('id','desc')->skip($nextID)->take(6);
        return $query->get();
    }
}

Because on Laravel Framework, I need create a new Model .php file Blog.php & Text.php to call eloquent method on controller eg : Blog::all(); or Text::listText(0,'rejected');

is there any way to share a global function or method like listData instead of listBlog or listText and not to copy and paste multiple time on Models.php? function on Laravel's Models file?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 BP神经网络控制倒立摆
    • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
    • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
    • ¥30 Unity接入微信SDK 无法开启摄像头
    • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
    • ¥20 cad图纸,chx-3六轴码垛机器人
    • ¥15 移动摄像头专网需要解vlan
    • ¥20 access多表提取相同字段数据并合并
    • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
    • ¥20 Java-Oj-桌布的计算