Laravel 5.1 - 从2个关系表中获取数据

时间:2016-05-18 12:17:52

标签: php laravel laravel-5

我在做电子商务,我为ORDERS创建了一个资源控制器。但是我有一些问题需要获得有关产品的信息。我想显示所有商品订单,其中包含有关所购产品的信息,如名称,价格,类别。每个订单商品都有“product_id”关系。 我有这个表迁移:

订单

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrderItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('orders_items', function (Blueprint $table) {
            $table->increments('id');
            $table->decimal('price', 5, 2);
            $table->integer('quantity')->unsigned();


            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')
                  ->references('id')
                  ->on('products')
                  ->onDelete('cascade');


            $table->integer('order_id')->unsigned();
            $table->foreign('order_id')
                  ->references('id')
                  ->on('orders')
                  ->onDelete('cascade');



         });





    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('order_items');
    }
}

订购商品

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */

    //Up creare table
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255);
            $table->string('slug'); 
            $table->text('description');

            $table->string('extract', 300);
            $table->decimal('price', 5, 2);
            $table->string('image', 300);

            $table->boolean('visible');


            $table->integer('user_id')->unsigned();

            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');







            $table->integer('category_id')->unsigned();

            // relazioni  
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories')
                  ->onDelete('cascade');
            //crea // Ogni prodotto ha un autore( artista)




            // ----// 
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    //eliminare table
    public function down()
    {
        Schema::drop('products');
    }
}

产品表

<?php

namespace dixard\Http\Controllers\Admin;

use Illuminate\Http\Request;

use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;

use dixard\Order;
use dixard\OrderItem;
use dixard\Product;
use dixard\Category;

use Validator;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $orders = Order::orderBy('id')->paginate(15);

        return view('admin.order.index', compact('orders'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view ('admin.order.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = [

                'status' => 'required',
                'method' => 'required',
                'order_code' => 'required',
                'fullname_ship' => 'required',
                'address_ship' => 'required',
                'app_ship' => 'required',
                'province_ship' => 'required',
                'country_ship' => 'required',
                'email_ship' => 'required',
                'phone_ship' => 'required',




        ];

        $messages = [


                'status.required' => 'Status ordine richiesto',
                'method.required' => 'Metodo di pagamento richiesto',
                'order_code.required' => 'Codice ordine richiesto',
                'fullname_ship.required' => 'Nome e cognome richiesto',
                'address_ship.required' => 'Indirizzo spedizione richiesto',
                'app_ship.required' => 'App/Interno richiesto',
                'province_ship.required' => 'Città/Provincia di spedizione richiesto',
                'country_ship.required' => 'Paese di spedizione richiesto',
                'email_ship.required' => 'Email campo richiesto',
                'phone_ship.required' => 'Cellulare/spedizione richiesto',



        ];


        $validator = Validator::make($request->all(), $rules, $messages);




        if ($validator->fails()){

         return redirect('admin/order/create')->withErrors($validator); 

        }else {

        $data = [

                'status' => $request->get('status'),
                'method' => $request->get('method'),
                'order_code' => $request->get('order_code'),
                'shipping' => $request->get('shipping'),
                'subtotal' => $request->get('subtotal'),

                'fullname_ship' => $request->get('fullname_ship'),
                'address_ship' => $request->get('address_ship'),
                'app_ship' => $request->get('app_ship'),
                'province_ship' => $request->get('province_ship'),
                'country_ship' => $request->get('country_ship'),
                'email_ship' => $request->get('email_ship'),
                'phone_ship' => $request->get('phone_ship'),

                'fullname_bill' => $request->get('fullname_bill'),
                'address_bill' => $request->get('address_bill'),
                'app_bill' => $request->get('app_bill'),
                'province_bill' => $request->get('province_bill'),
                'country_bill' => $request->get('country_bill'),
                'email_bill' => $request->get('email_bill'),
                'phone_bill' => $request->get('phone_bill'),

        ];

        $order = Order::create($data);

        return redirect('admin/order')->with('message', 'Ordine creato!');

        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Order $order)
    {
        $items = OrderItem::orderBy('id', 'desc')->paginate(20);
        $items_product_id = $items->product_id;

        $items_products=Product::with('items_product_id')->get();

        //$products = Product::where('id', $items->product_id)->orderBy('id', 'desc');




        return view('admin.order.show', compact('items','items_products'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Order $order)
    {
       return View('admin.order.edit', compact('order'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Order $order)
    {
        $id= $order->id;

        $rules = [

                'status' => 'required',
                'order_code' => 'required',
                'shipping' => 'required',
                'subtotal' => 'required',
                'fullname_ship' => 'required',
                'address_ship' => 'required',
                'app_ship' => 'required',
                'province_ship' => 'required',
                'country_ship' => 'required',
                'email_ship' => 'required',
                'phone_ship' => 'required',

            ];

            $messages = [


                'status.required' => 'Status ordine richiesto',
                'order_code.required' => 'Codice ordine richiesto',
                'shipping.required' => 'Costo spedizione richiesto',
                'subtotal.required' => 'Totale costo prodotti - SUBTOTAL richiesto',

                'fullname_ship.required' => 'Nome e cognome richiesto',
                'address_ship.required' => 'Indirizzo spedizione richiesto',
                'app_ship.required' => 'App/Interno richiesto',
                'province_ship.required' => 'Città/Provincia di spedizione richiesto',
                'country_ship.required' => 'Paese di spedizione richiesto',
                'email_ship.required' => 'Email campo richiesto',
                'phone_ship.required' => 'Cellulare/spedizione richiesto',



            ];


            $validator = Validator::make($request->all(), $rules, $messages);
            if ($validator->fails()){

                return redirect()->route('admin.order.edit', $id)->withErrors($validator)->withInput();

            }
            // if there is not any error go to update
            else{           

                // if email id different by input, so if email input update also email


                $s = new Order;

                $data = array(


                'status' => $request->get('status'),
                'method' => $request->get('method'),
                'order_code' => $request->get('order_code'),
                'shipping' => $request->get('shipping'),
                'subtotal' => $request->get('subtotal'),

                'fullname_ship' => $request->get('fullname_ship'),
                'address_ship' => $request->get('address_ship'),
                'app_ship' => $request->get('app_ship'),
                'province_ship' => $request->get('province_ship'),
                'country_ship' => $request->get('country_ship'),
                'email_ship' => $request->get('email_ship'),
                'phone_ship' => $request->get('phone_ship'),

                'fullname_bill' => $request->get('fullname_bill'),
                'address_bill' => $request->get('address_bill'),
                'app_bill' => $request->get('app_bill'),
                'province_bill' => $request->get('province_bill'),
                'country_bill' => $request->get('country_bill'),
                'email_bill' => $request->get('email_bill'),
                'phone_bill' => $request->get('phone_bill'),

                );



                $s->where('id', '=', $request->get('id'))->update($data);

                return redirect('admin/order')->with('message', 'Ordine aggiornato con successo!');
                }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Order $order)
    {
        $deleted=$order->delete();

        if(isset($deleted)) 
        {

        return redirect('admin/order')->with('message', 'Ordine eliminato con successo!');  


        } else {


        return redirect('admin/order')->with('message-error', 'Ordine non eliminato');  


        }
    }
}

我的OrderController.php

@foreach($items as $item)
                          <tr class="even pointer">

                            <td class=" ">{{ $item->id }}</td>
                            <td class=" ">{{ $item->product_id }}</td>
                            <td class=" ">{{ $item->quantity }}</td>
                            <td class=" ">€{{ $item->order_id }}</td>
                            </td>
                            </td>
                          </tr>

                          @endforeach

                          @foreach($items_products as $items_product)
                          <tr class="even pointer">

                            <td class=" ">{{ $items_product->id }}</td>
                            <td class=" ">{{ $items_product->name }}</td>
                            <td class=" ">{{ $items_product->price }}</td>
                            <td class=" ">€{{ $items_product->description }}</td>
                            </td>
                            </td>
                          </tr>

                          @endforeach

我创建了视图show.blade.php来显示所有订购的商品,我想显示所有商品的信息,包括名称,价格,类别。每个订单商品都有“product_id”关系。

我在show.blade.php中尝试这样做:

namespace dixard;

use Illuminate\Database\Eloquent\Model;

use dixard\User;

use dixard\Category;

use dixard\OrderItem;

class Product extends Model
{

    protected $table = 'products';

    protected $fillable = 

    [
    'name',
    'slug',
    'description',
    'extract',
    'image',
    'visible',
    'price',
    'category_id',
    'user_id'

    ];


    public function user() {
            return $this->belongsTo('dixard\User');

    }


    public function category() {
            return $this->belongsTo('dixard\Category');

    }

    public function OrderItem() {
            return $this->belongsTo('dixard\OrderItem');

    }


}

但它不起作用。谢谢您的帮助!如果你需要型号:

产品型号     

<?php

namespace dixard;

use Illuminate\Database\Eloquent\Model;

use dixard\Product;

class OrderItem extends Model
{
    // DIrgli che ci lascia scrivere 

    protected $table = 'orders_items';
    protected $fillable = [

    'price',
    'quantity',
    'product_id',
    'order_id'


    ];
    public $timestamps = false;
    public function product() 
    {

        return $this->hasMany('dixard\Product');    

    }


}

订购商品模型

<?php

namespace dixard;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    // DIrgli che ci lascia scrivere 

    protected $table = 'orders';


    // gli dico che voglio scrivere questo campi
    protected $fillable = [

    'subtotal',
    'shipping',
    'method',
    'status',
    'order_code',
    'fullname_ship',
    'address_ship',
    'app_ship',
    'province_ship',
    'country_ship',
    'email_ship',
    'phone_ship',
    'fullname_bill',
    'address_bill',
    'app_bill',
    'province_bill',
    'country_bill',
    'email_bill',
    'phone_bill',




    ];
}

订购模式

{{1}}

0 个答案:

没有答案