如何在laravel中调用模型中的函数?

时间:2016-03-31 06:54:38

标签: php laravel laravel-5

我正在使用Laravel构建一个应用程序,这对我来说是新的,我想在模型中创建任何方法,我将从某些Controller中的那些模型调用该方法,但我不知道它是好的还是遵循Laravel结构或不是因为Codeigniter让开发人员做那件事。

如何在Eloquent中使用此结构而不是使用原始sql 查询? 因为我使用$data = self::select("*")->get();查询数据时没有数据。

这是我的模特

    <?php
/**
 * Created by PhpStorm.
 * User: SOPHEAK Heng
 * Date: 16/03/31
 * Time: 10:29 AM
 * Notification Module
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Notification extends Model {

    protected $table = 'notification';
    public $timestamps = false;

    public function __construct(array $attributes)
    {
        parent::__construct($attributes);
    }
     public static function queryData() {

    $data = self::all();
    return $data;
    }
}

这是控制器:

<?php
/**
 * Created by PhpStorm.
 * User: SOPHEAK Heng
 * Date: 5/25/2015
 * Time: 5:40 PM
 */

namespace App\Http\Controllers;
use App\Models\Notification;

class MyController extends Controller
{ 

    public function __construct()
    { 
        $t = $this->sendDataToView();
        var_dump($t);
    }
    public function sendDataToView() {

        $test = new Notification();
        return $test->queryData();
    }

}

当我尝试使用 Eloquent 时,这是我的结果 似乎知道表,但在那里看不到任何数据 enter image description here

1 个答案:

答案 0 :(得分:1)

你在laravel中使用了错误的模型和控制器。你应该使用范围
模型和控制器应该是这样的

模型

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Notification extends Model {

    protected $table = 'notification';
    public $timestamps = false;



   public function scopeData($query)
    {
        return $query->where('done', 1);
    }


}

控制器

namespace App\Http\Controllers;
use App\Models\Notification;

class MyController extends Controller
{ 
    public function __construct()
    { 

    }
    public function sendDataToView() {
    $notification =  Notification::data()->get();
    return view('view file',compact('notification'));

    }

}

查看档案

 @foreach($notification as $noty)
  $noty->foo
 @endforeach

我希望对你有所帮助

相关问题