【问题标题】:Laravel 3: Is there a way to create an Eloquent model for your many-to-many pivot table?Laravel 3:有没有办法为你的多对多数据透视表创建一个 Eloquent 模型?
【发布时间】:2013-03-13 13:12:41
【问题描述】:

我要做的是添加与我的数据透视表的关系。我有一个独特的场景,我的数据透视表需要它自己在角色表上的 has_one 关系。有人看到专门为数据透视表创建 Eloquent 模型有问题吗?另外,如果我要创建这个模型,有什么方法可以让下面的模型返回?

$user = User::where('id', '=', 1);
$pivot = $user->hasmanyexample()->pivot();

我特别希望能够做到以下几点:

$user = User::where('id', '=', 1);
$pivot = $user->example()->pivot();

// class Example_User 
// public function role() { return $this->has_one('Role', 'role_id'); }
$role = $pivot->role(); 

【问题讨论】:

    标签: laravel eloquent laravel-3


    【解决方案1】:

    首先你必须制作一个 Pivot 模型,在我的例子中,我有 3 个模型

    • Edition->has_many_and_belongs_to('Format);
    • 格式->has_many_and_belongs_to('Edition);

    生成的数据透视表将被称为 edition_format,当我创建模型时,您首先必须创建一个目录 Edition,并在该文件夹中创建一个名为 format.php 的文件,这样您将拥有以下内容:

    -application/models/Edition/format.php

    那你要改表名,因为 laravel 找的是复数形式(edition_formats),关系需要 edition_format,所以你要在下面加上:

    class Edition_format extends Eloquent
    

    {

    public static $table = "edition_format";
    
    
    /* whatever you want */
    

    }

    那么你可以这样称呼它:Edition_format::find(1);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-05
      • 2021-02-13
      • 2020-05-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      相关资源
      最近更新 更多