格式化返回的数据库对象


Formatting returned Database Objects Laravel

我(终于)开始使用Laravel多年来主要使用CI进行开发,并且想知道如何确保我返回的所有数据库行都以相同的"格式"返回。例如,在Codeigniter中,我可以这样做:

<?php
Class Users_model extends CI_Model
{
 public $user_id;
 public $name;
 public $profile_image;
 public $status;
 const STATUS_ACTIVE   =  1;
 const STATUS_INACTIVE =  0;
 const STATUS_DELETED  = -1;

 function getById($user_id)
 {
    // typecasting
    $user_id = (int) $user_id;
    // database query
    $this->db->where('id', $user_id);
    $q = $this->db->get('users');
    // fetch the user record
    $row = $result->row();
    // set user values
    $this->user_id       = $row->id;
    $this->name          = $row->name;
    $this->profile_image = $row->image;
    $this->status        = $row->status;
    // return
    return $this;
 }
 function getListOfUsers()
 {
    // select 
    $this->db->select('id');
    // where query
    $this->db->where('status', self::STATUS_ACTIVE);
    // exectute query
    $q = $this->db->get('users');
    // get query results
    $results = $q->results();
    // set up default return
    $return = array();
    // loop through db results
    foreach($results as $r)
    {
        $u = new Users_model();
        $return[] = $u->getById($r->id);
    }
    return $return;
 }
}
?>

这是一个小的例子,但是这个类将使我能够确保我对数据库用户的所有调用都通过一个单一的函数(getByID)运行-显然,出于性能原因,所有内容都被大量缓存。在Laravel中应用相同逻辑的最佳方式是什么?显然,我可以编写自己的模型类,但使用Laravel而不使用Eloquent ORM似乎很愚蠢。如有任何帮助,我将不胜感激。

我试了如下:

<?php namespace App'Models;
use Illuminate'Database'Eloquent'Model;
class Products extends Model {
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'products';
/**
* set the constants
*
*/
const TYPE_USER        = 0;
const TYPE_STYLIST     = 1;
const STATUS_INACTIVE  = 0;
const STATUS_ACTIVE    = 1;
/**
* set the cache constants
*
*/
const CACHE_KEY    = 'Product/%d';
const CACHE_LENGTH = 86400;
public $product_id;
public $store;
public $name;
public $slug;
public $url_string;
function getProduct()
{
    $this->product_id = (int) 1;
    $this->store      = (int) 23;
    $this->name       = (string) 'Nike Air Max';
    $this->slug       = (string) 'nike-air-max';
    $this->url_string = (string) 'http://asos.com';
    return $this;
}
}
?>
但是获得所有不必要的类信息(显然),更重要的是,我不知道如何使用Eloquent函数(如 )来应用它。
$users = User::all();

感谢阅读

如果我理解正确的话,你可以在Eloquent中执行以下操作。

$tryThis = Your'Product'Model::find($id)

这将返回ID匹配的所有字段。更重要的是,它将作为一个集合返回,就像您使用Eloquent ORM编写的任何其他查询一样。

那么你可以像这样访问一个集合;

$tryThis->id;