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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝