首页 文章

使用背包包的laravel中 table 之间的关系

提问于
浏览
1

我正在使用backpack CRUD包在laravel 5.2中创建我的网站项目

我想在两个表之间 Build 关系 . 第一个表称为客户,第二个表称为事务 . 每个客户都有很多交易(1:N关系) .

客户表记录:

ID名称

123456 xyz

交易表记录:

ID CustomerID

101010 123456

我知道我必须在客户模型中指定关系 . 但是,如何在CRUD中显示关系的结果?

3 回答

  • 1

    您应该在Transaction和Customer模型上都有关系,因此您可以执行 $customer->transactions$transaction->customer

    class Customer extends Model
    {
        /**
         * Get the comments for the blog post.
         */
        public function transactions()
        {
            return $this->hasMany('App\Transactions', 'CustomerID', 'ID');
        }
    }
    

    class Transaction extends Model
    {
        /**
         * Get the comments for the blog post.
         */
        public function customer()
        {
            return $this->belongsTo('App\Customer', 'CustomerID', 'ID');
        }
    }
    

    花一些时间在Eloquent Relationships Documentation . 如果您想成为Laravel开发人员,了解它们非常重要 .

    为了在CRUD中显示关系,您可以使用Backpack的select column type在表格视图中显示它,并使用selectselect2字段类型在添加/编辑视图中显示它 . 阅读CRUD Example Entity以更好地了解其工作原理 .

  • 0

    首先,当您为两个表创建迁移时,包含外键(FK)的表必须具有以下字段:

    public function up(){
       $table->increments('id');
       $table->integer('customerID')->unsigned();
    }
    

    之后,您需要将下一个命令调用到控制台中

    php artisan migrate
    

    接下来是下一个命令:

    php arisan backpack:crud customers
    php arisan backpack:crud transactions
    

    之后,您需要在模型中定义函数,这些函数返回其他表中的值 . 客户模型需要具备下一个功能

    public function transactions(){
       return $this->hasMany('Transaction');
    }
    

    事务模型必须具有下一个功能

    public function customer() {
        return $this->belongsTo('Customer');
    }
    

    接下来,您必须在Customer控制器中添加CRUD字段以在选择框中显示事务 .

    $this->crud->addField([
       'label' => 'Transactions', // Label for HTML form field
       'type'  => 'select2',  // HTML element which displaying transactions
       'name'  => 'customerID', // Table column which is FK for Customer table
       'entity'=> 'customer', // Function (method) in Customer model which return transactions
       'attribute' => 'ID', // Column which user see in select box
       'model' => 'Transaction' // Model which contain FK
    ]);
    

    希望这可以帮助 :)

  • 3

    在与事务 Build onetomany关系后,您可以获得结果 .

    $customer=Customer::where(['id'=>'123456'])->with('transaction')
                                               ->first();
    
    print_r($customer->Name);  // gives the customer name
    foreach($customer->transaction as $cid)
    {
         print_r($cid->CustomerID);       // gives the customer id
    }
    

    Laravel Relationships Documentation总是有帮助的 . 通过它 .

相关问题