php's db class library Eloquent alone series (1)
php's db class library Eloquent alone series (2) - paging
php's db class library Eloquent alone series (3) - sql log
php db class library Eloquent used alone series (4) - event monitoring
php's db class library Eloquent used alone series (5) - model to array
php's db class library Eloquent used alone series (6) - one-to-one association with
php's db class Library Eloquent used alone series (7) - one-to-many association
php's db class library Eloquent used alone series (8) - many-to-many association
php's db class library Eloquent used alone series (9) - many-to-many association - table association
The db class library Eloquent of its own php uses the series (10) - many-to-many association - remote one-to-many
php db class library Eloquent uses the series (11) - many-to-many association - adding model attributes
php's db class library Eloquent Single use series (12) - result set model to array - 2
The purpose of this series of articles is to use Eloquent out of the laravel environment, because it is easy to use .
All codes in this series of articles have passed the test. Eloquent Version: 5.4.27
The purpose of this article is the extra properties of the model.
First create a table, assuming there is an active table act, each table has an area attribute area_id, which is associated with the area table, and the area table has a name field.
Now I want the activity model to have an area_name property automatically
then
Act.php
<?php namespace app\model; use \Illuminate\Database\Eloquent\Model; /** * Active model class */ class Act extends Model { protected $table = 'act'; public $timestamps = false; protected $appends = ['area_name']; // add additional properties here protected $hidden = ['city']; //If not written like this, the city model will be added // custom properties // The name of this method is very particular, and the underscore is converted to camel case. // When getting attributes, use $act->area_name public function getAreaNameAttribute() { return $this->city->name; // The name property is in the city table. } // This is the general definition, since a city will have multiple events associated with it public function city() { return $this->belongsTo('app\model\Area', 'area_id', 'id'); } }
client code
$act = \app\model\Act:find(1); echo $act->area_name;