I want to make a one-to-many relationship like in the tutorial.
~~~
One To Many
An example of a one-to-many relation is a blog post that "has many" comments. We can model this relation like so:
class Post extends Eloquent {
public function comments()
{
return $this->hasMany('Comment');
}
}
~~~
So i want to make a Model Post (connected to table "posts") and a Model Comment (connected to table 'comments'). I am creating the tables in phpMyAdmin and not with migrations (because i have no SSH support on the online server). The comments table has a column 'posts_id'.
Can i use ...
$comments = Post::find(1)->comments;
..without defining a foreign key relationship between the two tables in phpmyadmin?
And if the answer is YES.
Should i make a column name "post_id" or something like this in my 'comments' table or something for this to work? Just like you would do with a normal foreign key?
You don't have to explicitly declare a foreign key in the MySQL side but you have at least to create a post_id column that will be used by Laravel as a foreign key.
Of course, you can name this column as you want and specify it in the declaration of the relation :
class Post extends Eloquent {
public function comments()
{
return $this->hasMany('Comment', 'post_primary_key');
}
}
You can also declare this column as a foreign key in PHPMyAdmin to improve robustness of your database but that's not Laravel business.
Related
I use hibernate as the framework for springboot CUBA operations. But I have a problem, our workout information and recipe information are coming from external API. This means that I only need to store the recipe and workout ids in the database. The database structure is as follows.
DB sturucture
As the data is provided by the API, we have not created corresponding entity tables for workouts and recipes. But then the problem arises. What should be done with the join table in this case. I mean the premise of #manytomany is that two entity tables are needed, and we only have entity tables for users. Even if we use a joint primary key, there is still a need to add user_id as a foreign key in the joint primary key. How can we mark user_id as a foreign key without a workout or recipe entity table?
Your question is quite confusing but I'll try to provide an answer for what I understood.
If the data is completely external, you can map an element collection consisting of ids only:
#Entity
public class User {
// other fields
#ElementCollection
#CollectionTable(name = "recipse_user")
Set<Long> recipeIds;
#ElementCollection
#CollectionTable(name = "workout_user")
Set<Long> workoutIds;
}
I'm using Laravel and Mysql.
I'm trying to come up with a name for my pivot table where one column is a foreign key to the products table and the other column is a foreign key to the users table. I want the table name to be product_point_of_contact. I don't want to call the table product_user as that doesn't really explain what the table does. My columns would be product_id and user_id. I don't want to name the user_id column point_of_contact_id because I don't have a point_of_contacts table.
What is the convention and best option for this? Would you also create a PointOfContact model and extend it to use the User model?
The Laravel convention is:
To determine the table name of the relationship's intermediate table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method:
return $this->belongsToMany(Role::class, 'role_user');
In addition to customizing the name of the intermediate table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
So, if your models are Product and User, and you name the intermediate table as product_point_of_contact, and the fk product_id and user_id.
In your User model use:
return $this->belongsToMany(Product::class, 'product_point_of_contact');
In your Product model use:
return $this->belongsToMany(User::class, 'product_point_of_contact');
And you will not need to specify the foreign keys, since these do comply with the convention.
Said that...
What is the convention and best option for this?
IMO, the one you (and your team) can understand, and makes sense in the business logic of your application. Even if you/they read the code or the name of the tables within 6 months.
Would you also create a PointOfContact model and extend it to use the User model?
Not needed, you can use the User model. What I would do here would be to name the relationship with the meaning I want to give. For example:
class Product extends Model
{
/**
* The product point of contact (which is an user).
*/
public function pointOfContact()
{
return $this->belongsToMany(User::class, 'product_point_of_contact');
}
}
product_user will be the best since laravel itself will create the table name in alphabetical order, i advice you use product_user.
I was recently using Sequelize the ORM.
I have two tables. One is Users and the other is Posts
The schema of these two tables are as follows
Users {
id: Integer,
name: String,
age: Integer
}
Posts {
id: Integer, // refers to the id of post itself
author_id: Integer, // refers to the id of the author of this post
title: String,
content: String
}
I want to create an one(Users)-to-many(Posts) association between them. In order to do that, I need to specify the hasMany & belongsTo in the models.
However, I am very confused about the meaning of the parameters foreignKey / sourceKey / targetKey.
Say that I already define and create my table with migrations. The name of the attribute which is the foreignKey is author_id in this case.
My guess is, in belongsTo, foreignKey means "the name of the attribute that is going to be foreignKey in the source table"?
But in hasMany, foreignKey means "the name of the attribute that is referenced by the coming foreignKey"
So, foreignKey in belongsTo will be author_id (in table Posts) but foreignKey in hasMany will be id (in table Users) ?
Furthermore, what on earth do the sourceKey/targetKey mean!?
Well... you have an interesting case above... if you used user_id instead of author_id then you might get away without declaring these as sequelize might assume them correctly... However because you named it author_id then your hasMany definitely needs to know that the foreign key is named author_id in your post table... Let's say that you named your id in the user table something like "user" instead of "id".... well sequelize won't understand that and be able to infer what it is joining on, so you would say the the sourceKey = "user" and foreignKey = "author_id"... To further that one more you may run into issues in database design where you need to specify what the targetKey or otherKey is because someone was naming things whacky... so like you said above in your belongsTo author_id would have no clue that it was supposed to map back to "user" for it's join, so you would specify foreignKey = "author_id" and otherKey = "user"... This stuff took me a while to wrap my head around as well because i did not get to design the database i implements graphql/sequelize against... Therefore i had to make wide use of sourceKey, targetKey, and otherKey etc etc in my joins..
Try and think of it really logically and it will make more sense... if your primary key is always "id" and your foreignKey is always "tablename_id" then you won't need to worry too much about the other properties.. but when naming doesn't line up, sequelize needs to be told what keys to use, and that is why those other properties exist.. Sequelize is damn smart, but it can't make up for poor db design or bad join column naming... Hope this helps, if not i have plenty of examples i can post for you.. Cheers
I am trying to model with Laravel a database for purchases, in my mysql the relations are [ (for each table in the mysql i have one model)
so I was modeling in Laravel, for the associative table "fornecedor_item_detalhe" I used relation "belongstoMany", it worked out using tinker.
Now comes the problem:
together with the detalhes("fornecedor_detalhe") and the "items" I would like to be able to access the other tables related to "fornecedor_detalhe" which are "fornecedor" and "formpagto"."Has Many Through" will work For this?
And also I would like to link this associative table "fornecedor_detalhes-Item" in relation n: m with another table to create another associative table "fornecedor_detalhe_item_rci".
I've created a model for the pivot table "fornecedor_detalhe_item", but I'm not exactly sure how to do that, as long pivot tables don't have a primary key, how can i reference to them in the other pivot table
I did not codify anything, I'm just trying to model the same thing in laravel.
If you have any suggestions about MER I also accept it.
Thank you
just use Eloquent: Relationships
look in this link realtion types
and you should have model for fornecedor and formpagto
by build relation in model hasMany or belongsTo as your database structure you can call the anywhere just by type relation name
for example
in User Model
public function post()
{
return $this->hasMany(Post::class);
}
when you call in blade $user->post you get all posts related to this user and so on
I'm trying to set a string column as a primary key of a table, then reference that from another table as a foreign key. Is this possible? Per the documentation:
Laravel assumes every table has a numeric primary key (usually named “id”) and ensures the value of this column is unique for each new row added to the table. Laravel doesn’t really work well unless each table has a numeric primary key. So, for your average Laravel application, please ensure that you define a primary key using the increments() method.
In my case, I don't want to define an id column as it would be useless. The string column I want to define will act as a primary key. If this is possible, can I get an example migration snippet?
This is an old question, but for the sake of correctness I'd like to point out that in the current versions of Eloquent you can indeed use non numeric primary/foreign keys.
One thing you need to do is to set the property $incrementing to false on the models that use non autoincrementing ids.
class Employee extends Model
{
public $incrementing = false;
// ...
}
also, the migration can be something like this:
Schema::create('employees', function (Blueprint $table) {
$table->string('id')->primary();
// ...
});
More details why it cannot be string in Eloquent may be found in this forum archive.
Also, to the comment: Eloquent conforms the normalization rules. Althought, SQL supports foreign keys to be strings or integers without difference, you should consider adding an integer format keys to your application to make use of Eloquent, that is using generally accepted integer keys.