donglankui1263 2016-03-29 02:39
浏览 65
已采纳

无法显示Laravel 5.2中多对多关系的元素

im trying to query data from a Many to Many relationship in Laravel 5.2 But when I want to retrieve the data im getting blank information. I have some doubts because the data I received only detect quick_tags but theres is no data in there and it should be quickTags.

I'm doing this in my controller

<?php

namespace Knotion\Http\Controllers;

use Illuminate\Http\Request;
use Knotion\Http\Requests;
use Knotion\Http\Requests\ResourcesRequest;

use Knotion\CTL_Resource;
use Knotion\CTL_Tag;
use Knotion\CTL_QuickTag;
use Knotion\CTL_RelatedTo;
use Knotion\CTL_ResourceType;


class ResourcesController extends Controller  {

    public function index(Request $request)    {

        $resources = CTL_Resource::paginate(10);



        $resources->each(function($resources) {
          $resources->tags;
          $resources->quickTags;
          $resources->relatedTo;

        });

        return response()->json(
          $resources->toArray()
      );
    }

and I have this code in my Model

<?php

namespace Knotion;

use Illuminate\Database\Eloquent\Model;

class CTL_Resource extends Model  {
    public $timestamps = false;

    protected $table = "CTL_Resource";
    protected $primaryKey = "idResource";

    protected $hidden = [
      'coachVisibility', 'thumbnail', 'tags', 'relatedTo',
      'studentVisibility', 'isHTML','studentIndex', 'coachIndex',
      'isURL', 'source', 'path', 'status', 'updateTime', 'isfolder',
      'parentResource', 'idModifierUser'
    ];

    protected $fillable = ['idResourceType','productionKey', 'tags', 'idCreatorUser', 'idModifierUser', 'idCreationCountry', 'title', 'description', 'URL', 'fileName', 'extension', 'minimumAge', 'maximumAge', 'productionKey'];

    public function creatorUser() {
      return $this->belongsTo('Knotion\OPR_User', 'idCreatorUser');
    }
    public function creationCountry() {
      return $this->belongsTo('Knotion\CTL_Country', 'idCreationCountry');
    }
    public function resourceType()  {
      return $this->belongsTo('Knotion\CTL_ResourceType', 'idResourceType');
    }
    public function quickTags() {
      return $this->belongsToMany('Knotion\CTL_QuickTag', 'CTL_Resource_has_QuickTags', 'idResource','idQuickTag');
    }
    public function tags() {
      return $this->belongsToMany('Knotion\CTL_Tag','CTL_Resource_has_Tags', 'idResource', 'idTag');
    }
    public function relatedTo() {
      return $this->belongsToMany('Knotion\CTL_RelatedTo', 'CTL_Resource_has_RelatedTo', 'idResource', 'idRelatedTo');
    }

}

This is the result. As you see there is quick_tags and its empty

{
  "total": 2,
  "per_page": 10,
  "current_page": 1,
  "last_page": 1,
  "next_page_url": null,
  "prev_page_url": null,
  "from": 1,
  "to": 2,
  "data": [
    {
      "idResource": 0,
      "idResourceType": "49ee39d6-eecd-11e5-b044-4914876a7f3d",
      "idCreatorUser": "04664624-eecd-11e5-b044-4914876a7f3d",
      "idCreationCountry": "b4afa9ae-eecc-11e5-b044-4914876a7f3d",
      "productionKey": "1234567890",
      "title": "ElTitle1",
      "description": "ElDescription1",
      "minimumAge": "5",
      "maximumAge": "10",
      "fileName": "ElFileName1",
      "extension": ".png",
      "URL": "ElURL1",
      "createTime": "2016-03-28 14:07:21",
      "quick_tags": []
    },
    {
      "idResource": 0,
      "idResourceType": "49ee39d6-eecd-11e5-b044-4914876a7f3d",
      "idCreatorUser": "04664624-eecd-11e5-b044-4914876a7f3d",
      "idCreationCountry": "b4afa9ae-eecc-11e5-b044-4914876a7f3d",
      "productionKey": "0987654321",
      "title": "ElTitle2",
      "description": "ElDescription2",
      "minimumAge": "5",
      "maximumAge": "10",
      "fileName": "ElFileName2",
      "extension": ".png",
      "URL": "ElURL2",
      "createTime": "2016-03-28 14:44:37",
      "quick_tags": []
    }
  ]
}

I don't know if its necessary but this is the sql code of the relationship. I just posting this one but others are very similar

DROP TABLE IF EXISTS `CTL_Resource_has_QuickTags`;
CREATE TABLE `CTL_Resource_has_QuickTags` (
  `idResource` varchar(40) NOT NULL COMMENT 'Foreign key to the CTL_Resource table ',
  `idQuickTag` varchar(40) NOT NULL COMMENT 'foreign key to the CTL_QuickTags table.',
  PRIMARY KEY (`idResource`,`idQuickTag`),
  KEY `fk_CTL_Resource_has_QuickTag_QuickTag1_idx` (`idQuickTag`),
  KEY `fk_CTL_Resource_has_QuickTag_CTL_Resource1_idx` (`idResource`),
  CONSTRAINT `fk_CTL_Resource_has_QuickTag_CTL_Resource1_idx` FOREIGN KEY (`idResource`) REFERENCES `CTL_Resource` (`idResource`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_CTL_Resource_has_QuickTag_QuickTag1_idx` FOREIGN KEY (`idQuickTag`) REFERENCES `CTL_QuickTags` (`idQuickTag`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='this table establishes the amount of quicktags that a given tag';
  • 写回答

1条回答 默认 最新

  • dongsu3654 2016-03-29 06:26
    关注

    Considering your idResource is displaying as 0, as well as some similar fields look like GUIDs and your foreign key fields are defined as varchar(40), I'm going to assume that your CTL_Resource.idResource field is also defined as varchar(40).

    In this case, when the $primaryKey field is not an auto-incrementing integer, you need to tell the Model that. You do this by setting the $incrementing property on the Model:

    public $incrementing = false;
    

    Additionally, in relation to your quick_tags vs quickTags question, that has to do with the $snakeAttributes property on your Model. When set to true (which is default), your model will snake_case the keys of your relationship objects when converting to json (toJson()) or an array (toArray()). If you want to turn this off, you need to set the $snakeAttributes property on the Model:

    public static $snakeAttributes = false;
    

    So, your Model should end up looking something like:

    class CTL_Resource extends Model  {
    
        // set the table name since it is not ctl_resources
        protected $table = "CTL_Resource";
    
        // set the primary key field since it is not id
        protected $primaryKey = "idResource";
    
        // primary key is not an auto-incrementing int
        public $incrementing = false;
    
        // no created_at, updated_at fields on this table
        public $timestamps = false;
    
        // don't snake case the relationship names on json/array conversion
        public static $snakeAttributes = false;
    
        // code ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度