在模型关系

时间:2017-01-19 07:28:28

标签: php laravel laravel-5

我有两种模式:报告和用户。这就是我的用户模型中的内容

public function userReport() {
    return $this->hasMany('App\Report', 'user_id','id');
}

这是在报告模型中

public function user() {
    return $this->hasOne('App\User', 'id', 'user_id');
}

控制器

public function details( $item_id ){

    $report = Item::find($item_id)->report;
    return view('details', compact('report'));
} 

在视图中

{!! $report->user->name !!}

在视图中,我显示了报告单个项目的所有用户..我按$item_id查询。

问题是,如果同一用户报告单项1+时间,我会在页面上的表格中看到此用户1次以上。

是否有可能以某种方式按user_id分组或计算user_id并显示User1 ( 4 time reported ) ...?我应该把它们分组在哪里?

更新:用户表

id | username | password

报告表

report_id | id | user_id | date

项目表

id | user_id | category | date_added | image

Update2 :db中记录的图像。此处user_id=3的用户报告item_id=14总共14次。使用user_id=5的用户报告的item_id=14共计3次。我应该在页面user_id=3 ( 14 )user_id=3 ( 3 )上看到。相反,我看到17次user_id=3。贝娄是图像

enter image description here

在页面上

enter image description here

2 个答案:

答案 0 :(得分:1)

如何解决问题应该有几种方法

一种方法是(你的控制器看起来像)

batch_size = int(data_num_.shape[0]/10)

original_dim = data_num_.shape[1]

latent_dim = data_num_.shape[1]*2

intermediate_dim = data_num_.shape[1]*10

nb_epoch = 10

epsilon_std = 0.001



data_untrain = data_scale.transform(df[(df['label']==cluster_num)&(df['prob']<threshold)].iloc[:,:data_num.shape[1]].values)

data_untrain_num = (int(data_untrain.shape[0]/batch_size)-1)*batch_size

data_untrain = data_untrain[:data_untrain_num,:]



x = Input(batch_shape=(batch_size, original_dim))

init_drop = Dropout(0.2, input_shape=(original_dim,))(x)

h = Dense(intermediate_dim, activation='relu')(init_drop)

z_mean = Dense(latent_dim)(h)

z_log_var = Dense(latent_dim)(h)





def sampling(args):

    z_mean, z_log_var = args

    epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.,

                              std=epsilon_std)

    return z_mean + K.exp(z_log_var / 2) * epsilon

z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])


decoder_h = Dense(intermediate_dim, activation='relu')

decoder_mean = Dense(original_dim, activation='linear')

h_decoded = decoder_h(z)

x_decoded_mean = decoder_mean(h_decoded)





def vae_loss(x, x_decoded_mean):

    xent_loss = original_dim * objectives.mae(x, x_decoded_mean)

    kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)

    return xent_loss + kl_loss



vae = Model(x, x_decoded_mean)

vae.compile(optimizer=Adam(lr=0.01), loss=vae_loss)



train_ratio = 0.9

train_num = int(data_num_.shape[0]*train_ratio/batch_size)*batch_size

test_num = int(data_num_.shape[0]*(1-train_ratio)/batch_size)*batch_size



x_train = data_num_[:train_num,:]

x_test = data_num_[-test_num:,:]



vae.fit(x_train, x_train,

        shuffle=True,

        nb_epoch=nb_epoch,

        batch_size=batch_size,

        validation_data=(x_test, x_test))



# build a model to project inputs on the latent space

encoder = Model(x, z_mean)

x_test_predict = data_scale_.inverse_transform(vae.predict(x_test, batch_size=1))

x_test = data_scale_.inverse_transform(x_test)   

for idx in range(x_test.shape[1]):

    plt.plot(x_test[:,idx], alpha=0.3, color='red')

    plt.plot(x_test_predict[:,idx], alpha=0.3, color='blue')

    plt.show()

    plt.close()

第二种方式应该是在视图中使用public function details( $item_id ){ $report = Item::find($item_id)->report->unique('user_id'); return view('details', compact('report')); } 并检查唯一值。

第三种方法应该是在控制器中使用@foreach并使用控制器内的计算摘要准备唯一数据,然后将准备好的数据传递给查看。

您想要使用哪种解决方案只是一个选择问题。

希望它可以帮到你

答案 1 :(得分:1)

试试吧。希望它有所帮助

Report::where('item.id', $item_id)
    ->select('item.*','users.*',DB::raw('count(reports.report_id) as total'))
    ->join('item', 'item.id', '=', 'reports.id')
    ->join('users', 'users.id', '=', 'reports.user_id')
    ->groupBy('reports.report_id','reports.id')
    ->get();