我有一个Eloquent模型,它在我的一个表中创建新条目。我遇到的问题是每次页面运行时都会反复插入数据。如何检查该表中是否已存在该数据,如果该数据不存在,则插入该特定数据?
foreach($xml as $product) {
//var_dump($product); die;
Order::where('id', '=', $product->reference)->update(
array(
'invoice_id' => $product['orderid'],
'shipped' => $product['shipped'],
'processed' => $product['processed'],
'problem' => $product['problem'],
)
);
$tracking = new OrderTrack();
$tracking->invoice_id = $product['orderid'];
$tracking->shipper = $product->shipping->shipper;
$tracking->shipping_method = $product->shipping->shipping_method;
$tracking->shipping_date = $product->shipping->shipping_date;
$tracking->shipping_cost = $product->shipping->shipping_cost;
$tracking->tracking_number = $product->shipping->tracking_number;
if(!empty($product->shipping->shipping_notes)) {
$tracking->shipping_notes = $product->shipping->shipping_notes;
}
$tracking->save();
echo'done';
}
OrderTrack是我关注的代码部分。无论行是否已存在,它都将创建一个新条目。
$ xml var_dump
object(SimpleXMLElement)[294]
public 'order' =>
array (size=15)
0 =>
object(SimpleXMLElement)[295]
public '@attributes' =>
array (size=7)
...
public 'reference' => string '3053' (length=4)
public 'reference2' =>
object(SimpleXMLElement)[310]
...
public 'reference3' =>
object(SimpleXMLElement)[311]
...
public 'invoice' =>
object(SimpleXMLElement)[312]
...
public 'order_date' => string '2014-08-14 03:00:06' (length=19)
public 'billing_date' => string '2014-08-14 00:00:00' (length=19)
public 'changed' => string '2014-08-14 13:02:15' (length=19)
public 'sender' =>
object(SimpleXMLElement)[313]
...
public 'receiver' =>
object(SimpleXMLElement)[314]
...
public 'shipping' =>
object(SimpleXMLElement)[315]
...
public 'products' =>
object(SimpleXMLElement)[316]
...
1 =>
object(SimpleXMLElement)[296]
public '@attributes' =>
array (size=7)
...
public 'reference' => string '3054' (length=4)
public 'reference2' =>
object(SimpleXMLElement)[328]
...
public 'reference3' =>
object(SimpleXMLElement)[329]
...
public 'invoice' =>
object(SimpleXMLElement)[330]
...
public 'order_date' => string '2014-08-13 22:00:02' (length=19)
public 'billing_date' => string '2014-08-14 00:00:00' (length=19)
public 'changed' => string '2014-08-14 13:02:20' (length=19)
public 'sender' =>
object(SimpleXMLElement)[331]
...
public 'receiver' =>
object(SimpleXMLElement)[332]
...
public 'shipping' =>
object(SimpleXMLElement)[333]
...
public 'products' =>
object(SimpleXMLElement)[334]
...
答案 0 :(得分:0)
利用firstOrNew
$tracking = OrderTrack::firstOrNew(array('invoice_id' => $product['orderid']));
$tracking->invoice_id = $product['orderid'];
$tracking->shipper = $product->shipping->shipper;
$tracking->shipping_method = $product->shipping->shipping_method;
$tracking->shipping_date = $product->shipping->shipping_date;
$tracking->shipping_cost = $product->shipping->shipping_cost;
$tracking->tracking_number = $product->shipping->tracking_number;
if(!empty($product->shipping->shipping_notes)) {
$tracking->shipping_notes = $product->shipping->shipping_notes;
}
$tracking->save();