Laravel一对多CRUD示例

时间:2014-08-03 20:46:09

标签: php mysql laravel-4 one-to-many

我是Laravel的新手。我想用 Laravel4 将数据插入某些主要详细信息表。我在互联网上搜索,找不到合适的解决方案。

我有两个(加一个)表,如下所示。

PO_HEADER

PO_HEADER_ID
SUBJECT
PO_DATE 

PO_DETAIL

PO_DETAIL_ID
PO_HEADER_ID
DESCRIPTION
AMOUNT
QTY
UNIT_OF_MEASURE_ID

UNIT_OF_MEASURE

UNIT_OF_MEASURE_ID
UNIT_OF_MEASURE

我应该能够在按下 SAVE BUTTON 的同时在一次拍摄中插入PO主控制器和尽可能多的PO详细记录。详细信息部分中的度量单位应为下拉列表(从UNIT_OF_MEASURE表中填充)

请建议如何轻松实现这一目标。提前谢谢!

1 个答案:

答案 0 :(得分:0)

这取决于您的模型设置是否正确:

class PurchaseOrder extends \Eloquent
{
    protected $fillable = [
        'subject',
        'date'
    ];

    public function detail()
    {
        return $this->hasMany('PurchaseOrderDetail');
    }
}

class PurchaseOrderDetail extends \Eloquent
{
    protected $fillable = [
        'description',
        'amount',
        'qty'
    ];

    protected $with = [
        'unitOfMeasure',
    ];

    public function header()
    {
        return $this->belongsTo('PurchaseOrder');
    }

    public function unitOfMeasure()
    {
        return $this->hasOne('UnitOfMeasure');
    }
}

class UnitOfMeasure extends \Eloquent
{
    protected $fillable = [
        'name'
    ];

    public function lineItems()
    {
        return $this->belongsToMany('PurchaseOrderDetail');
    }
}

您还需要使用正确的设置来设置迁移,例如:

//migration for purchaseorder table
public function up()
{
    Schema::create('purchaseorders', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('subject');
        $table->string('date');
        $table->timestamps();
    });
}

//migration for purchaseorderdetail table
public function up()
{
    Schema::create('purchaseorderdetails', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('purchaseorder_id')->unsigned()->index();
        $table->integer('unitofmeasure_id')->unsigned()->index();
        $table->foreign('purchaseorder_id')->references('id')->on('purchaseorders');
        $table->string('description');
        $table->float('amount');
        $table->float('qty');
        $table->timestamps();
    });
}

//migration for unitsofmeasure table
public function up()
{
    Schema::create('unitsofmeasure', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

我希望,这应该让你非常接近你需要的东西。 :)然后你可以像这样查询你的项目:

$po-details = PurchaseOrderDetail::with(['purchaseOrder', 'unitOfMeasure')->find($id);

这是一个过于简化的控制器方法可能是这样的:     

class PurchaseOrderController
{
    public function show($id)
    {
        $purchaseOrders = PurchaseOrder::with('detail')->find($id);

        return View::make('purchaseOrder.show', compact('purchaseOrders'));
    }
}

然后你的看法:                                @foreach($ purchaseOrders as $ purchaseOrder)                              @foreach($ purachseOrder->详细信息为$ lineItem)                                      @endforeach             @endforeach