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

报告相同问题?

悬赏问题

  • ¥20 Linux上make出现错误不知道怎么解决
  • ¥15 prism提示我reinstall prism 如何解决
  • ¥15 asp.core 权限控制怎么做,需要控制到每个方法
  • ¥20 while循环中OLED显示中断中的数据不正确
  • ¥15 这个视频里的stm32f4代码是怎么写的
  • ¥15 JNA调用DLL报堆栈溢出错误(0xC00000FD)
  • ¥15 请教SGeMs软件的使用
  • ¥15 自己用vb.net编写了一个dll文件,如何只给授权的用户使用这个dll文件进行打包编译,未授权用户不能进行打包编译操作?
  • ¥50 深度学习运行代码直接中断
  • ¥20 需要完整的共散射点成像代码