Get value of relation of pivot table laravel

时间:2017-06-12 16:55:48

标签: php laravel laravel-5

Model ListDeals

class ListsDeals extends Model
{
protected $table = "deals";

protected $fillable = ['title', 'slug', 'description', 'price', 'has_discount', 'price_to_discount', 'price_reduced', 'status', 'approved', 'suspended', 'start_date', 'end_date'];

public function lists()
{
    return $this->belongsToMany('App\Models\Lists', 'list_has_deals' , 'deal_id', 'list_id')->withPivot('list_id');
}

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

Model Lists

class Lists extends Model
{

protected $table = "lists";

protected $fillable = ['title', 'slug', 'short_description', 'description', 'website', 'email', 'phone', 'lat_map', 'lng_map', 'address_reference', 'video', 'renewal_date', 'status', 'approved', 'suspended'];

public function categories()
{
    return $this->belongsToMany('App\Models\ListsCategories', 'list_has_categories' , 'list_id', 'category_id');
}

public function deals()
{
    return $this->belongsToMany('App\Models\ListsDeals', 'list_has_deals' , 'list_id', 'deal_id');
}

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

Pivot Table list_has_deals

id
list_id
deal_id

Controller HomePageController

namespace App\Http\Controllers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Models\User;
use App\Models\Lists;
use App\Models\ListsCategories;
use App\Models\ListsDeals;
use DB;

class HomePageController extends Controller
{

public function homepage(){

    $matchThese = [ 'suspended' => 0, 'status' => 1, 'approved' => 1 ];

    $deals = ListsDeals::where( $matchThese )->limit( 3 )->offset( 0 )->orderBy( 'start_date' )->get();

    return view( "homepage" )
            ->with( "deals", $deals );

}

}

I want get in the view the same categories of the list for the deal in the HomePageController, but i dont kwno thw way, i try with withPivot('list_id') but i dont get the id of the list, thank for the help.

1 个答案:

答案 0 :(得分:0)

Check out the section Retrieving Intermediate Table Columns

https://laravel.com/docs/5.4/eloquent-relationships#many-to-many