简体   繁体   中英

laravel 5.2 one pivot with many relations (belongstomany/polymorphic)?

he guys. i need your help.

i have three questions about logic and best practice in laravel/eloquent/relation.

first scenario

i have four models/tables.

1.) model: Ticket | db: tickets
2.) model: Status | db: status
3.) model: Comment | db: comments
4.) model: User | db: users
and
1.) one pivottable between Ticket and Status (status_ticket)

logicproblem:

1.) one ticket can have many status. (belongstomany/belongstomany)
2.) each status can have one comment (hasone/belongsto) and one user (hasone/belongsto) but only in combination with ticket (pivot:status_ticket).

my idea is to give the pivot table two addional cols (withPivot('user_id','comment_id'))

*) first question: how can i realize that construct?

second scenario the second question is the same as the first one but in these scenario how can i access "comment" not with hasone/belongsto rather with polymorphic-relation??

my db:

comments
    id - integer
    message - string

status
    id - integer
    name - string

tickets
    id - integer
    name - string

users
    id - integer
    name - string

third question what is the best way for naming the pivottable?

1.) 
status_ticket
    id - integer
    comment_id - integer
    status_id - integer
    ticket_id - integer
    user_id - integer

2.)
comment_status_ticket_user
    id - integer
    comment_id - integer
    status_id - integer
    ticket_id - integer
    user_id - integer

my solution:

i created a model for the pivottable. in the pivottablemodel i created a relation with morphOne (comment). info: the user_id is now in the comments db.

DB (pivot between status and ticket): status_ticket

id - integer
status_id - integer
ticket_id - integer

DB: comments

id - integer
message - string
user_id - integer
commentable_id - integer
commentable_type - string

MODEL: TicketStatus

namespace App;
use Illuminate\Database\Eloquent\Model;

class TicketStatus extends Model {

protected $table = 'status_ticket';
public $timestamps = true;

    public function comment() {     
        return $this->morphOne('App\Comment', 'commentable');
    }

}

stackoverflow: How to use multiple pivot table relationships

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