【问题标题】:How to manage relationships(fk) of models?如何管理模型的关系(fk)?
【发布时间】:2015-08-10 10:58:40
【问题描述】:

我知道如何创建模型 - php artisan make:model nameofmodel,我知道在迁移模型时我必须声明表将包含哪些列:

class CreateNameofmodelTable extends Migration {

     /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
     {
        Schema::create('nameofmodels', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('description');
            $table->timestamps();
        });
    }

   /**
   * Reverse the migrations.
   *
   * @return void
   */
   public function down()
   {
       Schema::drop('nameofmodels');
   }
}

但是如果我想使用 FK 关联两个模型,我必须在迁移文件或模型文件中设置哪些配置?

【问题讨论】:

    标签: php laravel-5 foreign-key-relationship laravel-artisan


    【解决方案1】:

    假设您有另一个表名为users 的模型用户。您可以在addressesusers 之间定义如下关系,

    public function up()
        {
            Schema::create('addresses', function(Blueprint $table)
            {
                $table->increments('id');
                $table->string('add1');
                $table->string('add2');
                $table->string('city');
                $table->string('contact_no');
                $table->enum('is_primary',['yes','no'])->default('no');
                $table->integer('user_id')->unsigned();
                $table->timestamps();
    
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            });
        }
    

    在用户模型类中,

    class User extends Model {
       /**
       * The table associated with the model.
       *
       * @var string
       */
        protected $table = 'users';
    
        public function addresses()
        {
            return $this->hasMany('App\Address');
        }
    
    }
    

    在地址类中

    class Address extends Model {
        /**
        * The table associated with the model.
        *
        * @var string
        */
       protected $table = 'addresses';
    
        public function user()
        {
            return $this->belongsTo('App\User');
        }
    
    }
    

    有关创建表的更多详细信息可以在 Laravel 上的官方Schema Docs 找到。还有更多关于关系的信息here

    更新

    根据this 的问题,您必须先创建引用表,然后再引用表。在我们的例子中,users 必须在您运行迁移以创建 addresses 表之前存在。

    简单用例

    假设,在控制器中你想知道特定用户有多少个地址,你可以这样做,

    $addressCount = User::find($userId)->addresses->count();
    

    请注意User::find($userId)->addresses返回相关模型的集合,而User::find($userId)->addresses()返回HasMany类型的对象

    你也可以像下面这样遍历集合,

    foreach(User::find($userId)->addresses as $address)
    {
        echo '<pre>';
        print_r($address);
    }
    

    另一方面,您可以获取与特定地址关联的用户,如下所示,

    $user = Address:find($addressId)->user; //returns object of type `User`
    echo $user->first_name;
    

    以下将工作

    $user = Address:find($addressId)->user(); //returns object of type `belongsTo`
    echo $user->first_name;
    

    注意,上面的Address:find($addressId)-&gt;user 不会返回集合,而是返回 User 类的单个对象。这是因为 belongsTo 关系。

    我希望我已经为您说明了一切。但没有什么比官方docs好。

    Laracast 视频更适合 Laravel。

    【讨论】:

    • 您能解释一下在用户和地址类中发生了什么吗?我的意思是,我知道函数adressesuser 具有告诉表之间的关系类型的功能,但是什么时候调用函数呢?
    • 我得到一个错误 150,它引用了 FK,我不确定 laravel 是否按照它们创建的顺序处理迁移,或者评估一个表是否必须在花药之前存在,因为fks
    【解决方案2】:

    你可以这样使用...

    class CreateNameofmodelTable extends Migration {
    
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('nameofmodels', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('description');
            $table->timestamps();
        });
    Schema::create('your table name', function(Blueprint $table) {
      $table->foreign('user_id')->references('id')->on('nameofmodels');
    }
    
    }
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('nameofmodels');
    }
    
    }
    

    检查一下..也许它工作得很好....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多