首页 > 解决方案 > Laravel 查询两个不相关的模型并从两者返回字段

问题描述

我有 2 个模型:

  1. 属性(字段:prop_id、a、b、c)
  2. OfferDemandmatch(字段:prop_id d、e、f)

两个模型都有prop_id列,必须使用它来连接两个模型。我有一个刀片视图,我在其中执行foreach匹配集合,并且我需要在每个集合项中包含来自 Property 和 OfferDemandmatch 模型的字段。

这是发送到 balde 视图的匹配集合的代码

class OfferdemandsmatchsController extends Controller
{
    public function index ($id) {
        $matchs = OfferDemand::findOrFail($id)->offerdemandsmatchs;
        return view('pages.processes.offerdemand.matchs.index', compact('matchs'));

    }
}

这是刀片视图中的代码

<div class="row">
  @foreach($matchs as $match)
      @component('pages.processes.offerdemand.matchs.matchbox')
      @endcomponent
  @endforeach
</div>

我需要foreach在刀片视图的每次迭代中使用属性和匹配字段。所以,我的收藏品必须包含以下字段:prop_id、a、b、c、d、e、f

我怎样才能做到这一点?

问候

标签: laravellaravel-5eloquent

解决方案


你好,我在电话里写,不能很好地解释,也不能格式化答案。

转到 laravel 文档并搜索如何进行交叉连接。这将加入两个数据库。

$data = DB::table('tbl_property')->crossJoin('tbl_offerdemand')->get();

编辑 1:在 prop_id 上正常加入

$data = DB::table('tbl_properties')->join('tbl_OfferDemandmatch', 'tbl_properties.prop_id', '=',  'tbl_offerdemand.prop_id') ->select() ->get();

推荐阅读