到达数据透视表字段Laravel 5.5

时间:2018-04-24 08:52:43

标签: laravel eloquent

我创建了3个表:

categories
    id
    admin_id
    created_at
    updated_at
    deleted_at

langs
    id
    langname_fr
    langname
    ....

我可以填写带有字段的数据透视表:

category_lang
    lang_id
    category_id
    catname
    catshortname
    ....

在控制器中我创建了一个方法index():

public function index()
{
    $categories = Category::with('langs')->get();
    $categoriesCount = Sector::count();
    return view('admin.pages.maps.index', compact('categories', 'categoriesCount'));
}

现在我想“到达”数据透视表中的字段...例如,如何在我的视图中显示“catname”?

这是我的模型(分类模型):

public function langs() {
    return $this->belongsToMany('App\Lang')
        ->withPivot(
            'sectname',
            'sectshortname',
            'sectdescription',
            'sectshortdescription',
            'created_at',
            'updated_at',
            'deleted_at'
        );
}

在视图中:

@foreach($categories as $category)
        <pre>
            {{ var_dump($category->pivot->catname) }}
        </pre>
@endforeach

它返回:尝试获取非对象的属性

4 个答案:

答案 0 :(得分:1)

您可以像这样添加->pivot个关键字:

@foreach($categories as $category)
    @foreach($category->langs as $lang)
        <pre>
            {{ var_dump($lang->pivot->catname) }}
        </pre>
    @endforeach
@endforeach

答案 1 :(得分:1)

public function langs() { return $this->belongsToMany(Category::class)->withPivot('catname'); } 模型中:

$categories->langs->pivot->catname

现在您可以检索数据......

{{1}}

参考:Laravel's Eloquent: Relationships

一篇好文章:Pivot tables and many-to-many relationships

答案 2 :(得分:0)

你可以使用另一个foreach循环来检索带有数据透视数据的lang,

@foreach($categories as $category)
        @foreach($category->langs as $lang)        
            {{ $lang->pivot->sectname }}
        @endforeach
@endforeach

答案 3 :(得分:0)

感谢我终于找到的所有答案:

[i.split(',') for i in response.xpath('//span[contains(@class, "genre")]/text()').extract()]