Laravel eloquent 加入三个 table

Laravel eloquent join three table

我是 Laravel 的新手。现在我需要一些关于加入 table eloquent.

的帮助

这是我的 table 结构,

产品Table

product_id    product_code    product_name
     1            1434            ABC

产品历史Table

history_id    product_id    cost    invoice_number
    1              1        100         ABC-01

产品导览Table

tour_id       product_id    provider_name
    1              1            TEST

现在我加入这 3 个 table,

$product =  product::join('product_history as ph', 'product.product_id', '=', 'ph.product_id', 'inner')
            ->join('product_tour as pt', 'product.product_id', '=', 'pt.product_id', 'inner')
            ->where('product.product_id', '1')
            ->get()
            ->toArray();

它工作正常。但我认为Laravel也提供了Eloquent关系。比如,hasOnehasManybelongsTobelongsToMany 等....

Any idea which method is use for my structure ?

提前致谢。

像这样更改您的查询:

$product =  product::Select("*")
            //->with('product_history','product_tour')
            //Use this with() for condition.
            ->with([
                   'ProductHistory' => function ($query){
                                    $query->select('*');
                   },
                   'ProductTour' => function ($query) use ($ProviderName) {
                                    $query->select('*')->where("provider_name", "=", $ProviderName);
                   },
            ])
            ->where('product.product_id', '1')
            ->get()
            ->toArray();

这是模型文件的代码:

namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function producthistory()
    {
        return $this->hasMany('App\ProductHistory', 'product_id','history_id');        
    }
    public function producttour()
    {
        return $this->hasMany('App\ProductTour', 'product_id','tour_id');        
    }

}

以及名为 Product_historyproduct_tour

的其他表的模型文件
namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductHistory extends Model
{    

    public function products()
    {
        return $this->belongsTo('App\Product', 'history_id','product_id');
    }

}

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductTour extends Model
{    

    public function products()
    {
        return $this->belongsTo('App\Product', 'tour_id','product_id');
    }

}