简体   繁体   中英

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 JOIN s 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?

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

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.

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