简体   繁体   English

没有实际外键的一对多关系

[英]One-to-many relationship without actual foreign key

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'). 所以我想做一个模型发布(连接到表“ posts”)和一个模型注释(连接到表“ comments”)。 I am creating the tables in phpMyAdmin and not with migrations (because i have no SSH support on the online server). 我正在phpMyAdmin中创建表,而不是进行迁移(因为在线服务器上没有SSH支持)。 The comments table has a column 'posts_id'. 注释表中有一列“ posts_id”。

Can i use ... 我可以用吗 ...

$comments = Post::find(1)->comments;

..without defining a foreign key relationship between the two tables in phpmyadmin? ..没有在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? 我应该在“注释”表中输入列名“ post_id”还是类似的名称,还是要使其起作用? 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. 您不必在MySQL端显式声明外键,但至少必须创建一个post_id列,该列将被Laravel用作外键。

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. 您还可以在PHPMyAdmin中将此列声明为外键,以提高数据库的健壮性,但这不是Laravel的事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM