我试图制作一个应用程序,您可以管理办公室材料,发票等。因此,我的订单包含许多材料和一个发票。
我的材料表有:
id | name | count_all | count_current | price_unit
我的订单表有:
id | count_order | material_id | invoice_id
我的发票表格包含:
id | number | inc_date | scan_name | sum
My Material模型如下:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Material extends Model
{
public function order(){
return $this->belongsTo('Order', 'material_id');
}
public function expenditure(){
return $this->belongsTo('Expenditure');
}
protected $fillable = [
'name', 'count_all', 'count_current', 'price_unit',
];
}
我的订单模型如下:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public function invoice(){
return $this->hasOne('App\Invoice');
}
public function material(){
return $this->hasMany('App\Material');
}
protected $fillable = [
'count_order',
];
}
我的OrderController看起来像:
<?php
namespace App\Http\Controllers;
use App\order;
use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\Controller;
class orderController extends Controller
{
/**
* Show a list of all of the application's orders.
*
* @return Response
*/
public function show()
{
$orders = DB::table('orders')->get();
return view('order', ['orders' => $orders]);
}
public function insert(Request $request){
$order = new order;
$order->count_order = $request->count_order;
$order->save();
return redirect('/order');
}
public function edit(order $order){
return view('edit_order', compact('order'));
}
public function update(Request $request, order $order){
if(isset($_POST['delete'])){
$order->delete();
return redirect('/order');
}
else{
$order->count_order = $request->count_order;
$order->save();
return redirect('/order');
}
}
}
因此,在尝试访问数据库时,我将使用功能&#34; show&#34;在我的路线。
我的刀片导致问题&#34;:
<tbody>
@foreach($orders as $order)
<tr>
<td>{{$order->id}}</td>
<td>{{$order->material->name}}</td> //this is causing the Undefined property problem when trying to display material name instead of id
<td>{{$order->invoice_id}}</td> //this should look similar to the one above but since it doesn't work I didn't change it
<td>{{$order->count_order}}</td>
<td>
<form action="/order/{{$order->id}}">
<button type="submit" name="edit" class="btn btn-primary">Edycja zamówienia</button>
{{ csrf_field() }}
</form>
</td>
</tr>
@endforeach
</tbody>
因此,当我尝试在刀片中显示材质名称时(如上所示),它会返回以下错误:
Undefined property: stdClass::$materials (View: C:\xampp\htdocs\laravel\petition_app\resources\views\order.blade.php)
答案 0 :(得分:2)
您需要使用belongsTo()
与order
之间的material
关系。将您的relationship
更改为:
public function material(){
return $this->belongsTo('App\Material','material_id');
}
您使用的是query builder
,您需要使用laravel eloquent
来访问relationship
模型数据。更改您的控制器logic
代码,如:
$orders = Order::all();