试图从每个人那里获取身份
$person = $request->input('person');
//values for person: Murdock,Wayne
$values = explode(',' , $person);
if(count($values) > 1) {
//count($values) = 2
foreach($values as $val) {
$get_id = Tag::where('name', $val)->get();
foreach($get_id as $get) {
echo "id=".$get->id;
$result= FileTags::with('file')->where('tag_id', $get->id)->get();
}
}
}
当我{id}获得id = 1时,被认为是id = 1且id = 2
默多克 - 身份:1
Wayne - id:2
echo $get->id
我应该获取id为2,3和4的文件
模型标签
|table filetags|
| id | tag_id | file_id |
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 2 | 4 |
| 4 | 3 | 1 |
$result = FileTags::with('file')->where('tag_id', $id->id)->get();
模型存档
public function fileTag() {
return $this->hasMany('App\FileTags');
}
模型文件标签
protected $table = 'files';
public function fileTag() {
return $this->hasMany('App\FileTags');
}
感谢您的帮助。
修改
public function tag() {
return $this->belongsTo('App\Tag' , 'tag_id');
}
public function file() {
return $this->belongsTo('App\Archive', 'file_id');
}
echo $ obt_id;
的结果 |table tag|
| id | name |
| 1 | Murdock |
| 2 | Wayne |
来自var_dump($ obt_id)
[{"id":1,"name":"Murdock","description":"Description","type":"0","status":"1","created_at":"2016-07-20 18:01:14","updated_at":"2016-07-20 18:01:14"}][]
答案 0 :(得分:0)
您可以创建变量$result
;将其初始化为空Array
,然后将所有评估代码的结果FileTags::with('file')->where('tag_id', $get->id)->get()
推送到$result
数组中。最后,检查$result
数组是否为空。如果不是,你可以简单地用逗号破坏它(假设它是一个字符串)并回显你的结果......
<?php
$person = $request->input('person');
//values for person: Murdock,Wayne
$values = explode(',' , $person);
$result = array(); // <== INITIALIZE TO AN EMPTY ARRAY...
if(count($values) > 1) { //<== $values NOT values...
//count(values) = 2
foreach($values as trim($val)) { //<== TRY TRIMMING OFF WHITE SPACES.
$get_id = Tag::where('name', $val)->get();
foreach($get_id as $get) {
echo "id=".$get->id;
// PUSH THE DATA INTO THE ARRAY...
$result[] = FileTags::with('file')->where('tag_id', $get->id)->get();
}
}
}
// CHECK IF $result IS NOT EMPTY
if(!empty($result)){
// CONVERT THE ARRAY TO A STRING (ASSUMING ITS CONTENT ARE NOT OBJECTS OR ARRAYS)
$result = implode(", ", $result);
// ECHO OUR YOUR RESULT...
echo $result;
}