这篇文章主要介绍了关于Laravel的Eloquent 模型的介绍,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
Eloquent 模型
默认继承use Illuminate\Database\Eloquent\Model类。
数据表名称与模型名称约定:
数据库的表名一般使用“蛇形命名法”命名。蛇形命名法要求单词小写,单词之间用_下划线连接,且名称是复数。
与之对应的模型名称,则使用“帕斯卡法“命名,即单词头一字母都大写。
如果不是按以上约定,则需指明对应的数据表:
class Flight extends Model{ /** * 与模型关联的数据表 * * @var string */ protected $table = 'myflights';}
主键:
模型默认数据表用id字段作主键,并且是递增整数类型。这些可以自定义:
class Flight extends Model{ /** * 与模型关联的数据表 */ protected $table = 'my_flights'; protected $primaryKey='mid'; //自定义主键字段 protected $keyType = 'string'; //自定义主键类型为字串 public $incrementing = false; //主键非自增型}
时间截:
模型默认存在created_at 和 updated_at两字段,可设定$timestamps不需两字段:
class Flight extends Model{ /** * 该模型是否被自动维护时间戳 */ public $timestamps = false;}
$dateFormat属性可自定义时间截格式存储在数据表的格式:
class Flight extends Mo<b>6本文来源gao@dai!ma.com搞$代^码!网7</b><pre>搞gaodaima代码
del{ /** * 模型的日期字段的存储格式 */ protected $dateFormat = 'U';}
自定义时间截字段名:
<?phpclass Flight extends Model{ const CREATED_AT = 'creation_date'; const UPDATED_AT = 'last_update';}
自定义数据库连接:
class Flight extends Model{ /** * 此模型的连接名称。 */ protected $connection = 'connection-name';}
模型查询:
use App\Flight;$flights = App\Flight::all(); //查询所有数据foreach ($flights as $flight) { echo $flight->name;}$flights = App\Flight::where('active', 1) ->orderBy('name', 'desc') ->take(10) ->get(); //有条件地查询数据
all和get方法返回 Illuminate\Database\Eloquent\Collection实例。
如果查询大批量数据,可使用chunk,可节省内存:
Flight::chunk(200, function ($flights) { foreach ($flights as $flight) { // }});
或使用游标方法cursor大幅度减少内存的使用:
foreach (Flight::where('foo', 'bar')->cursor() as $flight) { //}