【发布时间】:2019-01-23 22:22:36
【问题描述】:
我想知道是否可以在刀片中查询 hasOne -> hasMany 关系。我目前可以使用“$participant->messages->count()”计算我的刀片中存在多少模型,但我想检查模型并计算其他内容。例如,我想在刀片中运行以下查询:
{!! $participant->messages->where($this->messages->mediaURL, "=", null)->count() !!}
我收到以下错误:
Property [mediaURL] does not exist on this collection instance.
这是我的控制器功能
public function showParticipants()
{
$participants = Participant::all();
// $messages = $participants->participant_id->messages;
return view('home')->with(['participants'=> $participants, 'messages'=>'hi']);
}
我的 Participant 模型的一部分:
public function messages()
{
return $this->hasMany('App\Message', 'message_id', 'participant_id');
}
我的消息模型的一部分:
public function participant()
{
return $this->belongsTo(Participant::class);
}
我的消息表结构:
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('message_id')->unsigned();
$table->string('message_content')->nullable();
$table->string('mediaSID')->index()->nullable();
$table->string('messageSID')->index()->nullable();
$table->string('mediaURL')->index()->nullable();
$table->binary('media')->nullable();
$table->string('filename')->index()->nullable();
$table->string('MIMEType')->nullable();
$table->timestamps();
});
Schema::table('messages', function($table) {
$table->foreign('message_id')->references('participant_id')->on('participants')->onDelete('cascade');
});
}
我的参与者数据库结构:
public function up()
{
Schema::create('participants', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->string('participant_id')->unique();
$table->dateTime('appointmentDate')->nullable();
$table->dateTimeTz('timezoneOffset')->nullable();
$table->dateTime('appointmentDate_twoWeeks')->nullable();
$table->dateTime('notificationTime')->nullable();
$table->integer('notificationTally')->nullable();
$table->boolean('studyCompleted')->default(0);
$table->boolean('subscribed');
$table->timestamps();
});
}
我的刀片只是为了提供所有信息:
@isset($participants)
@foreach ($participants as $participant)
<tr>
<td>
{!! $participant->participant_id !!}
</td>
<td>
{!! $participant->subscribed !!}
</td>
<td>
{!! $participant->notificationTime !!}
</td>
<td>
{!! $participant->notificationTally !!}
</td>
<td>
{!! $participant->studyCompleted !!}
</td>
<td>
{!! $participant->messages->count() !!}
</td>
<td>
{!! $participant->messages->where($participant->messages->mediaURL, "=", null)->count() !!}
</td>
</tr>
@endforeach
@endisset
【问题讨论】:
标签: laravel laravel-5 eloquent relational-database laravel-blade