【问题标题】:Laravel query two models which are not related and return fields from bothLaravel 查询两个不相关的模型并返回两者的字段
【发布时间】:2020-06-17 08:28:54
【问题描述】:

我有 2 个模型:

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

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

这是发送到 balde view 的 Match 集合的代码

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

我怎样才能做到这一点?

问候

【问题讨论】:

  • 您需要提供更多信息,例如型号代码和对预期响应的更多解释。为什么不使用模型之间的关系?
  • 在最后一段中,他想要一个来自 2 个表的完全联接

标签: laravel laravel-5 eloquent


【解决方案1】:

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

转到 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();

【讨论】:

  • 谢谢@hmrneves!我查看了文档,并且 crossjoin 结合了所有值。我需要的是使用 prop_id 值加入两个模型并返回两个模型的字段。
  • 您好,两种方法都可以。我更新了答案以提供有关使用 prop_id 加入的示例。问候
  • 谢谢@hmrneves!我使用以下方法完成了这项工作:public function index ($id) { $matchs = DB::table('offerdemandsmatchs') -&gt;join('properties', 'offerdemandsmatchs.prop_id', '=', 'properties.prop_id') -&gt;where('offerdemandsmatchs.offerdemand_id', '=', $id) -&gt;select('properties.*', 'offerdemandsmatchs.*') -&gt;get(); dd($matchs); return view('pages.processes.offerdemand.matchs.index', compact('matchs')); }
  • 您好,您不需要选择属性。只使用 select() 因为你需要一切。
  • 没问题。我认为您不需要在哪里,因为您按 prop_id 过滤。但是你需要测试一下。hapoy 编码!
猜你喜欢
  • 2018-01-05
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 2021-03-30
  • 2021-02-02
  • 1970-01-01
相关资源
最近更新 更多