如何管理模型的关系(fk)


How to manage relationships(fk) of models?

我知道如何创建模型- 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关联两个模型,我必须在迁移文件或模型文件中设置哪些配置?

假设您有另一个表名为users的模型User。可以将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文档中找到。和更多关于关系的信息在这里

根据这个问题,你必须在引用表之前先创建引用表。在我们的示例中,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)->user将不会返回集合,而是返回User类的单个对象。这是因为belongsTo关系。

我希望我已经把事情说清楚了。但没有什么比官方文件更好的了。

Laracast视频更适合使用Laravel。

您可以这样使用…

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

检查一下,可能是正常工作....