【问题标题】:Laravel Polymorphic Relations problemsLaravel 多态关系问题
【发布时间】:2014-03-09 08:27:15
【问题描述】:

在这个link建议不要使用Polymorphic Relations

例如对于这个 Sql 命令,我们必须不带FOREIGN KEY

CREATE TABLE Comments (

    comment_id SERIAL PRIMARY KEY,

    comment TEXT NOT NULL,

    issue_type VARCHAR(15) NOT NULL CHECK (issue_type IN (`Bugs`, `Features`)),

    issue_id INT NOT NULL,

    FOREIGN KEY issue_id REFERENCES ???

);

那么我们一定有:

CREATE TABLE Comments (

    comment_id SERIAL PRIMARY KEY,

    comment TEXT NOT NULL,

    issue_type VARCHAR(15) NOT NULL CHECK (issue_type IN (`Bugs`, `Features`)),

    issue_id INT NOT NULL,

);

此命令在使用JOIN 或同时使用JOINs 时有问题,例如:

SELECT * FROM Comments c

LEFT JOIN Bugs b ON (c.issue_type = 'Bugs' AND c.issue_id = b.issue_id)

LEFT JOIN Features f ON (c.issue_type = 'Features' AND c.issue_id = f.issue_id);

这些问题只针对SELECT 其他问题是:UPDATE, DELETE

什么 laravel 方法来解决这个问题?

更新: 现在如何找到帖子所有者?

【问题讨论】:

    标签: mysql laravel laravel-4


    【解决方案1】:

    Laravel 有多态关系,见这里:http://laravel.com/docs/eloquent#polymorphic-relations

    您的数据库表设置相同(除了您需要使用commentable_idcommetnable_type 来处理以下代码示例),并且在您的模型中执行以下操作:

    class Comment extends Eloquent {
    
        public function commentable()
        {
            return $this->morphTo();
        }
    
    }
    
    class Bug extends Eloquent {
    
        public function comments()
        {
            return $this->morphMany('Comment', 'commentable');
        }
    
    }
    
    class Feature extends Eloquent {
    
        public function comments()
        {
            return $this->morphMany('Comments', 'commentable');
        }
    
    }
    

    然后你可以这样使用:

    $bug = Bug::find(1)->comments();
    

    您也可以采用其他方式,因此如果您只是获取一个 cmets 列表,您就可以获得该评论的所有者,而不知道它是什么:

    $comment = Comment::find(1);
    
    $commentable = $comment->commentable; 
    // this will load the bug or feature that the comment belongs to
    

    【讨论】:

    • 现在如何找到帖子所有者?
    • 更新了答案,在底部添加了一个部分来概述这个
    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 2014-11-11
    • 2016-03-08
    • 1970-01-01
    • 2019-11-25
    • 2019-05-06
    • 2014-05-24
    相关资源
    最近更新 更多