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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.