dtrj21373 2016-04-22 09:49
浏览 49
已采纳

Laravel Pivot具有多个价值观

I am trying to build a (slightly complex) subscription service using Laravel.

The subscriptions would be of the type: Breakfast Subscription for 20 breakfasts to be used within 30 days of enrolment.

For example, If user enrols for the breakfast subscription on 1st of April, he can avail for any 20 days of his choice, until April 30.

I've made the following tables and corresponding Models:

User Model and table

Users: 
- id
- name
- email
etc

Subscriptions table and Model

Subscriptions: 
- id
- name
- price
- validity 
- meals_available

subscription_user pivot (?) table with softDeletes

- subscription_id
- user_id
- start_date
- end_date
- created_at
- updated_at
- deleted_at

I've updated the corresponding models with belongsToMany relations ships

User:

class User extends Authenticatable
{
     ...
    /*
     * User can have many subscriptions
     */

    public function subscriptions()
    {
        return $this->belongsToMany('App\Subscription')->withTimestamps();
    }
}

Subscriptions Model

class Subscription extends Model
{
     ...
    /*
     * Subscription can have many Users
     */

    public function users()
    {
        return $this->belongsToMany('App\User')->withTimestamps();
    }
}

Issues that I need help with 1. Is the database/model structure correct way to solve the problem?

  1. While I can use attach() and detach() methods, I am not able to fill in start_date and end_date values in the subscription_table. How to do this?

  2. I want to use soft deletes on the pivot table. How I can use it?

Thanks in Advance.

展开全部

  • 写回答

2条回答 默认 最新

  • donglusou3335 2016-04-22 12:17
    关注
    1. Not sure yet.

    2. Attach method with additional columns. set models as:

    public function subscriptions()
    {
    return $this->belongsToMany('App\Subscription')
    ->withTimestamps()
    ->whereNull('subscription_user.deleted_at')
    ->withPivot('start_date','end_date');
    }
    

    You can update the rows as

    $user->subscriptions()->attach([1 => ['start_date' => '2016-04-01', 'end_date' => '2016-04-30'], 2, 3]);
    
    1. You can't use detach method for soft deletes. Update using a DB query.

    Optionally you may want to add methods like these to retrieve deleted rows for a give user.

     public function subscriptionsWithTrashed()
        {
            return $this->belongsToMany('App\Subscription')->withTimestamps()->withPivot('start_date','end_date');
        }
    
        public function subscriptionsOnlyTrashed()
        {
            return $this->belongsToMany('App\Subscription')->whereNotNull('subscription_user.deleted_at')->withTimestamps()->withPivot('start_date','end_date');
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?