Laravel Polymorphic Relations problems

in this link suggested to do not use Polymorphic Relations

for example for this Sql commands we must be without 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 ???

);

then we must be have :

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,

);

this command have problem for using JOIN or using simultaneously JOINs such as:

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);

those problems is only for SELECT other problem are: UPDATE, DELETE

whats laravel way to resolve this problems?

UPDATE: how to find post owner now?

Answers


Laravel has polymorphic relations, see here: http://laravel.com/docs/eloquent#polymorphic-relations

Your database table is setup the same (except you need to use commentable_id and commetnable_type to work with the following code sample), and in your models do something like this:

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');
    }

}

You can then use this like:

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

You can also go the other way, so if you just grab a list of comments, you can then get the owner of that comment, without knowing what it is yet:

$comment = Comment::find(1);

$commentable = $comment->commentable; 
// this will load the bug or feature that the comment belongs to

Need Your Help

Mass mailing HTML-newsletter in Asp.Net

asp.net html email newsletter mailing-list

I'm developing a site where I need to send HTML newsletters to a mailing-list.