1

バックパックCRUDパッケージを使用して、laravel 5.2でWebサイトプロジェクトを作成しています

2 つのテーブル間に関係を確立したいと考えています。最初のテーブルは customer と呼ばれ、2 番目のテーブルは transaction と呼ばれます。各顧客は多くのトランザクション (1:N の関係) を持っています。

顧客テーブル レコード:

ID名

123456 xyz

トランザクション テーブル レコード:

ID カスタマー ID

101010 123456

顧客モデルで関係を指定する必要があることはわかっています。しかし、関係の結果を CRUD で表示するにはどうすればよいですか?

4

3 に答える 3

4

$customer->transactionsTransaction モデルと Customer モデルの両方に関係が必要なので、以下を行うことができます$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 カラム タイプを使用してテーブル ビューに表示し、selectまたはselect2フィールド タイプを使用して追加/編集ビューに表示できます。CRUD Example Entityを読んで、その仕組みをよりよく理解してください。

于 2016-08-27T05:15:06.330 に答える
1

まず、両方のテーブルの移行を作成する場合、外部キー (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');
}

次に、顧客コントローラーに 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
]);

お役に立てれば :)

于 2016-09-01T17:37:33.963 に答える