【问题标题】:Laravel 5.4 - How to Responses JSON data with foreign key?Laravel 5.4 - 如何使用外键响应 JSON 数据?
【发布时间】:2017-08-09 17:57:52
【问题描述】:

我有两个表,我想用外键响应数据。

表格类别

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id',10);
            $table->string('name',100)->nullable();
            $table->timestamps();
        });
    }

桌歌

  public function up()
    {
        Schema::create('songs', function (Blueprint $table) {
            $table->increments('id',10);
            $table->string('name',100)->nullalbe();
            $table->string('url',500)->nullalbe();
            $table->integer('categories_id')->unsigned();
            $table->timestamps();

            $table->foreign('categories_id')->references('id')->on('categories');

        });
    }

类别模型

class CategoryModel extends Model
{
    protected $table = 'categories';
    protected $fillable = [
        'id',
        'name',
    ];
    public function song()
    {
        return $this->hasMany(SongModel::class);   
    }
}

歌曲模型

class SongModel extends Model
{
    protected $table = 'songs';
    protected $fillable = [
        'id',
        'name',
        'url',
        'categories_id',
        'singers_id',
        'types_id',
    ];

    public function category()
    {
        return $this->belongsTo(CategoryModel::class, 'categories_id');
    }
}

CategorySongController

class CategorySongController extends Controller
{

    public function index(CategoryModel $categoryModel)
    {
        $song = $categoryModel->song;
        return response()->json(['Data' => $song]);
    }

}

错误

SQLSTATE[42S22]:未找到列:1054 未知列 'where 子句'中的'songs.category_model_id'(SQL:select * from songs 其中songs.category_model_id 为空且 songs.category_model_id 不为空)

我的路线

Route::resource('/api/v1/categories', 'CategoryController', ['only' => ['索引', '显示',]]); Route::resource('/api/v1/categories.songs', 'CategorySongController', ['only' => ['index']]);

【问题讨论】:

  • return $this->hasMany(SongModel::class,'categories_id');替换return $this->hasMany(SongModel::class);
  • 我改变了,但它再次显示:使用未定义的常量 categories_id - 假定为 'categories_id'
  • 你用引号包裹了 categories_id 吗?
  • 对不起先生,云你解释一下?
  • 你能告诉我你添加的整行代码吗?

标签: php laravel-5


【解决方案1】:

问题出在CategoryModel 模型中的song 关系中,您当前的方法将尝试在songs 表中查找category_model_id,因为您没有在关系中提供任何外键

return $this->hasMany(SongModel::class); 替换为 return $this->hasMany(SongModel::class,'categories_id'); 以修复您的错误

【讨论】:

    【解决方案2】:

    尝试将 CategoryModel 中的方法名称 song() 更改为复数 songs()

    【讨论】:

      猜你喜欢
      • 2018-01-14
      • 2019-07-11
      • 2021-09-06
      • 1970-01-01
      • 2018-02-05
      • 2016-05-11
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      相关资源
      最近更新 更多