【发布时间】:2017-11-03 10:22:58
【问题描述】:
我试图弄清楚 Eloquent 是如何工作的,以及与使用普通 sql 查询相比的优势(在 columA.id = columnB.id 上连接 A 和 B 表...)
我有两个模型:多对多关系中的渠道和子类别
我创建了一个 channel_subcategory 数据透视表并添加了如下关系:
public function up()
{
Schema::create('channel_subcategory', function (Blueprint $table) {
$table->increments('id');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
$table->integer('channel_id')->unsigned()->nullable();
$table->foreign('channel_id')->references('id')->on('channels')->onDelete('cascade');
$table->integer('subcategory_id')->unsigned()->nullable();
$table->foreign('subcategory_id')->references('id')->on('subcategories') ->onDelete('cascade');
});
}
I want to get one channel given the slug property and the subcategories it belongs to. So I did this in the ChannelController.php
public function show($slug)
{
$channel = Channel::where('channels.slug', '=', $slug)->first();
foreach ($channel as $subcategory) {
echo $subcategory->title;
}
}
I get the error:
ErrorException in ChannelController.php line 107: Trying to get property of non-object
All I want is to show the channel name and the categories it belongs to.
我阅读了很多博客,包括 Laravel 文档,它们总是解释迁移、如何在模型中建立关系(属于自己的),甚至如何保存相关数据。但是我在任何地方都没有找到一个说明(针对假人),现在让我们从两个表中获取一些数据,例如:
- 获取一个频道所属的所有类别。
- 获取一个类别中的所有频道
- 获取属于多个类别的所有频道
- 获取频道更多的类别。
换句话说,一个关于如何做到这一点的简单解释。
编辑 添加我的频道模型
public function subcategory()
{
return $this->belongsToMany('App\Subcategory')->withTimestamps();
}
【问题讨论】:
标签: laravel eloquent many-to-many querying