我的频道模型为:
class Channels extends Model
{
protected $fillable = ['title','slug'];
public function Discussion()
{
return $this->hasMany('App\Discussion');
}
}
渠道模型为:
class Channels extends Model
{
protected $fillable = ['title','slug'];
public function Discussion()
{
return $this->hasMany('App\Discussion');
}
}
频道迁移文件:
class CreateChannelsTable extends Migration
{
public function up()
{
Schema::create('channels', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('channels');
}
}
讨论偏头痛文件
class CreateDiscussionsTable extends Migration
{
public function up()
{
Schema::create('discussions', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('channel_id')->unsigned();
$table->string('title');
$table->text('content');
$table->text('slug');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('discussions');
}
}
**控制器为:**
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function channel($slug)
{
$channel= Channels::where('slug',$slug)->first();
return view('channel')->with('discussion',$channel->Discussions);
}
}
最终路线是
Route::get('channel/{slug}',[
'uses' => 'HomeController@channel',
'as' => 'channel']);
**现在我正在尝试获取数据:**
$channel->Discussions
但这给了我错误
SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ discussions.channels_id”(SQL:从
discussions
中选择*,其中discussions
。channels_id
= 1和discussions
。channels_id
不为空)
我不知道现在该怎么办。请帮助我
答案 0 :(得分:1)
首先,正确命名类及其关系非常重要。
Laravel基于类名和关系定义对外键进行一些假设。如果需要,还可以指定外键。
但是,这就是我要做的。
class Channel extends Model
{
protected $fillable = ['title','slug'];
public function discussions()
{
return $this->hasMany('App\Discussion');
}
}
请注意,此处的型号名称称为Channel。当我们有了此类的名称和关系时,Laravel将假定讨论模型具有一个名为channel_id
的外键。
您还需要在“讨论”模型中定义逆关系
class Discussion extends Model
{
public function channel()
{
return $this->belongsTo('App\Channel');
}
}
现在,请执行以下操作:
public function channel($slug)
{
$channel = Channel::whereSlug($slug)->first();
return view('channel')->with('discussion', $channel->discussions);
}
如果您受束缚并且无论出于何种原因都无法更改模型名称,则需要在关系定义中指定外键。 例如:
public function discussions()
{
return $this->hasMany('App\Discussion', 'channel_id');
}
public function channel()
{
// This one can stay the same as Laravel will try to match `channel_id`
// on the discussion table to the id on the channels table
return $this->belongsTo('App\Channel');
}
有关更多信息,请阅读有关Eloquent Relationships的信息。
抱歉,@ Julien Metral评论时我已经在写这篇文章了,但这是他已经说过的话的延伸:)