Laravel Pivot具有多个价值观

时间:2016-04-22 17:49:34

标签: php mysql laravel

我正在尝试使用Laravel构建一个(稍微复杂的)订阅服务。

订阅的类型如下: 早餐订阅 20个早餐将在注册后30天内使用。

例如,如果用户在4月1日订购早餐,他可以选择任意20天,直到4月30日。

我制作了以下表格和相应的型号:

用户模型和表格

Users: 
- id
- name
- email
etc

订阅表和模型

Subscriptions: 
- id
- name
- price
- validity 
- meals_available
带有softDeletes的

subscription_user pivot(?)表

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

我已经使用belongsToMany关系发布了相应的模型

用户:

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

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

订阅模式

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

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

我需要帮助的问题  1.数据库/模型结构是否是解决问题的正确方法?

  1. 虽然我可以使用attach()和detach()方法,但我无法在subscription_table中填写start_date和end_date值。这该怎么做?

  2. 我想在数据透视表上使用软删除。我怎么用呢?

  3. 提前致谢。

2 个答案:

答案 0 :(得分:1)

要设置数据透视表中的值,您可以使用:

$user->subscriptions()->updateExistingPivot($subscriptionId, ['start_date' => '2016-01-01', 'end_date' => '2016-01-01']);

$user->subscriptions()->attach([1 => ['start_date' => '2016-01-01', 'end_date' => '2016-01-01'], 2, 3]);

并且要使用softDelete,您可以使用这些方法中的任何一种来更新deteled_at并检索以这种方式约束关系的数据

$this->belongsToMany('App\Subscription')->wherePivot('deleted_at','null');

答案 1 :(得分:0)

  1. 还不确定。

  2. 使用其他列附加方法。将模型设置为:

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

    您可以将行更新为

    $user->subscriptions()->attach([1 => ['start_date' => '2016-04-01', 'end_date' => '2016-04-30'], 2, 3]);
    
    1. 您不能将分离方法用于软删除。使用数据库查询进行更新。
    2. 或者,您可能希望添加这些方法以检索给定用户的已删除行。

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