laravel许多人检索数据

时间:2017-06-16 08:10:57

标签: laravel laravel-5 eloquent

我有很多关系,这就是我在做的事情:

在网址中,我正在传递Business表中的商家ID:

@foreach ($business as $businesses)
        <a target="_blank" href="{{ url('business/' . $businesses->id) }}"> {{($businesses->name) }}
        </a> @endforeach 

然后运行此函数:

public function displayBusiness($id) {
        $business = Business::find($id)->addresses;
        //return $business;
        //$address = Address::find($id);
        $session = session()->put('key', $id);
        $gallery = Gallery::where('business_id', $id)->get();
        $location = Location::where('business_id', $id)->get();
        $review = Review::where('business_id', $id)->get();
            return view('displayBusiness', compact('business', 'address', 'gallery', 'location', 'review'));
}

但问题是注释掉的行,带回与业务ID匹配的结果,但并非总是如此,因为有时业务ID = 1且地址id = 4但此代码将带回地址id = 1

所以我想做的是查看我的包含business_id和address_id的联结表,并使用$ id查找business_id以及与该id匹配的address_id。

退货业务给了我[]

所以我想要的是这样的:

我们假设$ id = 1 进入business_address并找到匹配1的business_id; 还可以找到与找到的business_id匹配的address_id, 将匹配ID返回到业务表并压缩匹配id的结果 地址表相同

我的模特:

Address.php

public function businesses() {
    return $this->belongsToMany(Business::class, 'business_address', 'business_id', 'address_id');
}

Business.php

public function addresses() {
    return $this->belongsToMany(Address::class, 'business_address', 'address_id', 'business_id');
}

1 个答案:

答案 0 :(得分:0)

我猜每个企业都有很多地址。
1.这将返回id为$id

的商家
$business = Business::find($id);

2。这将返回与该业务匹配的所有地址

$address = $business->addresses;

请注意,$address会返回集合而不是单个对象
如果有帮助,请告诉我