Skip to content

Instantly share code, notes, and snippets.

@zgulde
Last active February 1, 2016 01:30
Show Gist options
  • Save zgulde/2cb25c422d853fd70027 to your computer and use it in GitHub Desktop.
Save zgulde/2cb25c422d853fd70027 to your computer and use it in GitHub Desktop.

How to use the model classes

modifying a record

$user = UserModel::find(2);
echo $user->first_name; // echos 'Henry'
// change the user's first name
$user->first_name = 'Mike';
$user->save();

Note that when modifying an ad, only properties of the ad table can and will be changed. E.g. this code

$ad = AdModel::find(15);
$ad->title = 'new title';
$ad->user = 'new user'; // cant modify the user as it is not a part of the ads table

Will not work!

creating a new record

$user = new UserModel();

$user->email = 'test@example.com';
$user->first_name = 'test';
$user->last_name = 'user';
$user->password = 'pwd';

$user->save();

Once the save method is called, an id attribute will be added to the object, so you can get the id of the newly created record like so

$ad = new AdModel();
// put stuff in the relevant fields
$ad->save();
$newlyCreatedId = $ad->id; // contains the id of the newly inserted record

displaying info

for an individual record

$ad = AdModel::find(2);
...
// somewhere in the HTML
echo $ad->title;
echo $ad->category;
echo $ad->user;

for multiple records

$ads = AdModel::all();
...
foreach($ads as $ad){
    echo $ad['title'];
    echo $ad['price'];
    ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment