I'm a Symfony 2 developper who's beginning on Laravel. I'm a little bit lost with Laravel's ORM, it seems that we have to directly deal with the database to create tables manually... On Symfony, this was automatically made by Doctrine according to the mapping classes (and #ORM annotations).
Is the concept totally different on Laravel, or did I just not find the way to do it like on Symfony ?
Your question is not clear enough but I guess you want to know how Eloquent models map tables, in this case you have to use your table names (in database) the plural form of the word (but not mandatory), for example, a table that used to contain user data should be users or for post data the table should be posts but you may use whatever you want.
To map the users table with an Eloquent model; all you need to do i; create a model like this:
Post extends Eloquent {
//...
}
Now you may use something like this:
$posts = Post::all();
$post = Post::find(1);
Laravel will query from the posts table but if your table name is different than the standard way Laravel wants then you have to tell Laravel what is the table name by adding a property in the model, for example:
Post extends Eloquent {
protected $table = 'article'; // Laravel will query from article table
//...
}
You can use Post model as;
// Laravel will query from article table in the database
// because you gave the $table property with the table name
$posts = Post::all();
$post = Post::find(1);
Read more on the manual.
Laravel have migration like DoctrineMigrationsBundle, so in your model(entitie) you just write (for exemple):
class YourClass extends Eloquent {
}
So no need to overcharge your model with attribute, laravel do it automatically
http://laravel.com/docs/migrations for more information aboutmigration
Related
I'm just getting going with Laravel, and have used Eloquent to define my Campaign table. I have a Campaign model which is currently empty.
I'm not sure how to add attributes to this model to represent the fields in the db - or even if I should. The Laravel documentation seems thin on models and searches keep leading me to accessors and mutators.
If I have a database field called platform_type in my campaigns table, how do I link the PlatformType model attribute to this field?
To clarify:
This is not a question about relationships - there is only one entity in my solution thus far.
platform_type is a field in my campaigns table because it is an attribute of a campaign - I'm asking how to represent this in my model.
The model has an internal array which stores the attributes of a given row (it's called $attributes and replicated by $original if you look for them in the source code). The reason it's replicated is so when you call save() it will only do a save if you actually changed them from the originals.
You can access said attributes via $modelInstance->getAttribute("platform_type") or $modelInstance->platform_type which will call the magic __get method that in turn calls the getAttribute
So in your case you can have:
$campaign = Campaign::find($id);
echo $campaign->platform_type;
The ORM will automatically create the relevant SQL query and fill the model instance with the attributes of the row it finds.
You need to define relationships. In the PlatformType model:
public function campaigns()
{
return $this->hasMany(Campaign::class, 'platform_type');
}
And in the Campaign model:
public function platformType()
{
return $this->belongsTo(PlatformType::class, 'platform_type');
}
You also need to rename the campaign table to campaigns. Or you should add this to the model to be able to use a custom name:
protected $table = 'campaign';
At this point, these tables will be connected and relationships will work. However, it is recommended to add foreign key constraints.
my base class is post
and many submodel such as : video post , image post
all class have specific attribute & inherit parent attrib
& all class need specific behaviors
Problem
when find on post model elequent give super model(post) instance, its wrong
i need instance of submodel
If I understood you correctly, you need relationships
Add a hasMany relationship to your Post.php model:
public function videos()
return $this->hasMany(App\PostVideo::class);
}
As long as your post_video table has a post_id column that references a post, you can call this relationship like this:
foreach($post->videos as $video) {
// Do something
}
And the inverse relationship:
Add a relationship to your PostVideo.php model:
public function post() {
return $this->belongsTo(App\Post::class);
}
And of course, if you have a video, you can access the post it belongs to by doing:
$video->post
It is looked like you want a single table inheritance. In laravel this could be done manually or use package like nanigans or intrip. To use single table inheritance manually, i could suggest you start with reading this stackoverflow question first. However, notice that single table inheritance put everything in a single table but refered by several models that have different behavior. If this is not what you want, just use simple eloquent queries and models - which already explained by Pistachio.
So, i'm confused with this :
In Laravel's official documentation, they say :
The Eloquent ORM included with Laravel provides a beautiful, simple
ActiveRecord implementation for working with your database. Each
database table has a corresponding "Model" which is used to interact
with that table.
Ok util here all is Great, i get it !
So I make a migration to create a database : php artisan make:migration create_items_table --create="items"
Great until here too :)
So theoretically speaking, when i will make : php artisan make:model Item , Laravel will create a php class ( which is used to interact with items table) :
class Item extends Eloquent {
...
}
But,in real world, when i make : php artisan make:model Item , Laravel creates php class ( which is used to interact with items table) ::
class Item extends Model {
...
}
So Why Model and not Eloquent ?? Am i missing sth ?
And What's the difference between Eloquent Model and Model.
And if there's a difference, when should i use Eloquent and when Model ... ?
Thank you ^^
I found the solution for my question ...
So Normally you must add an alias to your config/app.php
'aliases' => [
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
And when you create a model, Laravel will use Eloquent; instead of use Illuminate\Database\Eloquent\Model; this why i think, some person may use Model, when other may use Eloquent , it's just a matter of give a meaning sense to the namespace :3
Eloquent is the name given to the ORM (Object-relational mapping) that ships with Laravel. Eloquent allows you to interact with your tables as though they were objects, however Eloquent is unaware of the actual columns you have on your table.
Let's consider the simple User model. We want this model to query records on our users table.
class User extends Eloquent {
protected $table = 'users';
}
That there is a very simple model. Now, instead of querying like this.
$user = DB::table('user')->find(1);
You can query like this.
$user = User::find(1);
Eloquent itself uses its own query builder but does fall back to the standard query builder. This means it has all the methods on the query builder available to it, and more.
The benefits here are:
You don't have to specify your table name on every call.
The code reads a whole lot better, it's syntactical sugar.
You can create complex relationships between tables and use eager loading.
You can make use of functionality such as mass assignment protection and setters/getter.
I've only touched on Eloquent. There is so much more to it. I suggest you take a look at the following resources.
Eloquent Documentation
Dayle Rees' Code Happy
For more exact simple example click here
I'm using laravel eloquent data objects to access my data, what is the best way to name my tables, columns, foreign/primary keys etc?
I found, there are lots of naming conventions out there. I'm just wondering which one best suits for laravel eloquent models.
I'm thinking of following naming convention:
Singular table names (ex: Post)
Singular column names (ex: userId - user id in the post table)
Camel casing for multiple words in table names (ex: PostComment, PostReview, PostPhoto)
Camel casing for multiple words in column names (ex: firstName, postCategoryId, postPhotoId)
So with this, I could use similar syntax in the controller.
$result = Post::where('postCategoryId', '4')->get();
Are there any recommended Laravel guidelines for this? Can I proceed with these naming conventions?
If someone has better suggestions, I will be very happy to hear them.Thanks a lot!
Laravel has its own naming convention. For example, if your model name is User.php then Laravel expects class 'User' to be inside that file. It also expects users table for User model. However, you can override this convention by defining a table property on your model like,
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'user';
}
From Laravel official documentation:
Note that we did not tell Eloquent which table to use for our User model.
The lower-case, plural name of the class will be used as the table name
unless another name is explicitly specified. So, in this case, Eloquent
will assume the User model stores records in the users table. You may specify a
custom table by defining a $table property on your model
If you will use user table id in another table as a foreign key then, it should be snake-case like user_id so that it can be used automatically in case of relation. Again, you can override this convention by specifying additional arguments in relationship function. For example,
class User extends Eloquent implements UserInterface, RemindableInterface {
public function post(){
return $this->hasMany('Post', 'userId', 'id');
}
}
class Post extends Eloquent{
public function user(){
return $this->belongsTo('User', 'userId', 'id');
}
}
Docs for Laravel eloquent relationship
For other columns in table, you can name them as you like.
I suggest you to go through documentation once.
I don't agree in general with these examples you both have shown right on here.
It is clean if you take a look at the official Laravel documentation, especially in the Eloquent's relationship session (http://laravel.com/docs/4.2/eloquent#relationships).
Table names should be in plural, i.e. 'users' table for User model.
And column names don't need to be in Camel Case, but Snake Case. See it is already answered: Database/model field-name convention in Laravel?
It is too usual you can see it is like the RedBeanORM: the Snake Case for columns, even if you try other one. And it is adviced to avoid repeating the table names with column ones due to the method you can call from the Model object to access their relationships.
class User extends Eloquent implements UserInterface, RemindableInterface {
public function post(){
return $this->hasMany('Post');
}
}
class Post extends Eloquent{
public function user(){
return $this->belongsTo('User');
}
}
The default table naming conventions can easily cause conflicts with the installation of multiple packages who may have incidentally the same class names. A solution would be to name tables as: [vendor].[package].[class], which is in line with how namespacing in Laravel is applied.
Edited: Using dots in table names is not recommended though. Would there be an alternative convention to use to ensure developers of a modular built application do not need to worry about existing table names.
I can't find anywhere the information on how you have several intermediate tables with your Eloquent ORM models. The problem I'm facing is that I have a table for my users, permissions and roles. These are the 4 tables:
Permissions:
id
name
Permission_roles:
id
name
Permission_role_mappings:
id
permission_id
permission_role_id
Permission_role_user_mappings:
id
permission_role_id
user_id
(Well, I also have a users table but the layout of it doesn't matter since the foreign key is in permission_role_user_mapping.)
So the problem is that I want to be able to get the data from the permissions table when calling from the User model. I have some trouble grasping the workflow with Eloquent ORM altogether so if I'm missing something basic which is crucial then please point it out.
According to the documentation it seems that I don't need to create models for the intermediate tables. So how would I specify the relationship from the User class? Could I do something similar to this?
class User extends Eloquent {
public function permission_role()
{
return $this->has_many_and_belongs_to('Permission_Role', 'permission_role_user_mappings');
}
public function permission()
{
return $this->has_many_and_belongs_to('Permission_Role', 'permission_role_user_mappings')->has_many_and_belongs_to('Permission','permission_role_mappings');
}
}
This doesn't seem to be working, this is the error:
User::find(1)->first()->permission()->first();
...
Method [permission] is not defined on the Query class.
I also want to be able to get data by starting from Permission_Role and Permission. I'd prefer that the answer would help me specifying all the models required.
Eloquent relationships are accessed as an object property instead of a function.
User::find(1)->first()->permission;
You can wrap that above statement in the dd function to get a look at it.
This guide on Eloquent Relationships should be helpful
Edit for question in comments about selecting all permissions in the role:
$roles = array();
$permission_roles = User::find(1)->permission_roles()->get();
foreach ($permission_roles as $pr) {
if (! in_array($pr->permissions)) {
$roles[] = $pr->permissions;
}
}
This will get you what you want. However, this will end up doing a lot of queries. It's best to make use of Eager Loading here.