drblhw5731 2019-04-18 09:15
浏览 108
已采纳

基于foreignKey Laravel从表中检索数据

So I have 2 tables, articles and sub_categories. They are linked throug Eloquent: articles has many sub_categories's, and sub_categories belongsTo article. They are linked with foreign keys as such: in "article" categorie_id.

How do I retrieve the entire table data article where categorie is "DOG" for exemple Sorry for the abstraction, but this is the best way I can explain it? :D

article model

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Articles extends Model
{
    use SoftDeletes;

    public function user() {
        return $this->belongsTo('App\User') ;
    }

    public function sous_categories() {
        return $this->belongsTo('App\SouCategories') ;
    }
}

sub_categorie model

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class SouCategories extends Model
{
    public function categories() {
        return $this->belongsTo('App\Categories') ;
    }

    public function articles() {
        return $this->hasMany('App\Articles','cat_id') ;
    }
}

in my controller i am trying to fetch data based on the foreign key on the sub_category and foreach sub category i am creating an a array like the mainslider contain articles that have a certain sub_category

public function index()
{
    $infos = Infos::all();
    $categories = Categories::all();
    $articles=Articles::all();   
    $mainslider=Soucategories::with('articles')->get();
    foreach($mainslider as $record){
        dd($record->articles);
    }
    die();
    return view('frontEnd.homepage',compact('infos','categories','articles','mainslider'));
}
  • 写回答

1条回答 默认 最新

  • duanrui3480 2019-04-18 09:37
    关注

    According to the code you have posted it should be something like

    Soucategories::where('title', 'DOG')->with('articles')->get();
    

    it seems there will be only on Soucategory with name "DOG", so you can do something like

    Soucategories::where('title', 'DOG')->first()->articles
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格