简体   繁体   English

从Laravel中的belongsToMany关系中检索数据

[英]Retrieving data from belongsToMany relationship in Laravel

I have some problems with getting data from my relationship. 从我的关系中获取数据时遇到一些问题。 I need the tags of some domains. 我需要某些域的标签。

$domains = Domains::where('customer_id', Auth::user()->customers_id)->get();

There are all the domains I need. 有我需要的所有领域。 On my Domains model I have this belongsToMany relation to my pivot table. 在我的Domains模型上,我的数据透视表具有这个EmiratesToMany关系。

public function tags() { 
    return $this->belongsToMany('App\Models\Tags_Domains', 'domain_tag', 'domains_id', 'tags_id'); 
}

I was able to get all the datas from my relation with this: 我能够从我的关系中获得所有数据:

dd($domains[0]->tags);

That gave me all the data I wanted but only for the very first domain. 这给了我所有我想要的数据,但仅用于第一个域。 But I want this for every domain, to pass this new array to my Blade template. 但是我希望每个域都可以将此新数组传递给我的Blade模板。 I tried many things out but couldn't make it work. 我尝试了很多方法,但是无法正常工作。 ( $collection error, trying to get properly of non-object ... ) ($ collection错误,试图正确获取非对象...)

Can someone help me there? 有人可以帮我吗?


Controller Code: 控制器代码:

    $domains = Domains::where('customer_id', Auth::user()->customers_id)->get();
    return view('defaultLayout.domains.tagsdelete', [
        'domains' => $domains
    ]);

This is because you use $domains[0] and you get the first domain. 这是因为您使用$ domains [0]并获得了第一个域。 You must loop through them: 您必须遍历它们:

foreach($domains as $domain) {
    foreach($domain->tags as $tag) {
        var_dump($tag);
    }
}

Edit: If you need the tags in your view here is how: 编辑:如果您需要视图中的标签,请按以下步骤操作:

@foreach($domains as $domain)
     <p>{{ $domain->name }}</p> //where name could be any field that $domain has
     @foreach($domain->tags as $tag)
     <p>{{ $tag->name }}</p> //where name could be any field that $tag has
     @endforeach
@endforeach

Glad I was helpful :) 很高兴我帮了大忙:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM