Retrieving data which doesn't exist in the other table - laravel-5

I have two tables SCHOLAR and MEMBER table. I want to display list of scholars from Scholar table which scholar_id doesn't found in Member table. But the result of my Second dd is empty which actually it has data in database. What am i doing wrong?I think my code is fine.
public function list()
{
$scholars = Member::all();
$scholar_ids = [];
foreach ($scholars as $scholar) {
array_push($scholar_ids, $scholar->scholar_id);
}
$scholar_exits = Scholar::where('scholar_id','=', $scholar_ids)->get();
<!-- First -->
dd($scholar_ids);
<!-- Second -->
dd($scholar_exits);
}
<!-- First dd result -->
array:7 [▼
0 => 7
1 => 8
2 => 12
3 => 13
4 => 14
5 => 15
6 => 16
]
<!-- Second dd result -->
Collection {#275 ▼
#items: []
}
Hope anyone can help me here.

What about
public function list()
{
$members = Member::all();
$members = $members->toArray();
$scholar_ids = array_pluck($members, 'scholar_id');
}
//Are you sure you do not want to refer to 'id' instead of 'scholar_id'?
$scholar_exits = Scholar::whereIn('scholar_id', $scholar_ids)->get();
}

public function list()
{
$scholars = Member::get(['scholar_id'])->toArray();
if(!is_null($scholars)) $scholars = array_flatten($scholars);
else $scholars = [];
$scholar_exits = Scholar::whereNotIn('scholar_id', $scholars)
->get();
}

Related

How to change collection column value in laravel

I have a laravel collection that's like this:
$loan = Loans::where([
['OL_TEMP_APP_NO', $appNo]
])
->get();
The $loan collection returns principal, terms, code. The code corresponds to a string. Example 1 = new, 2 = processing, 3 = approved.
How do I parse the values under code before sending them to the view?
You can use CASE WHEN to convert the integer to string code:
$loan = Loans::where([
['OL_TEMP_APP_NO', $appNo]
])
->select('principal', 'terms', DB::raw("
(CASE code
WHEN 2 THEN 'processing'
WHEN 3 THEN 'approved'
ELSE 'new' END) AS code
"))
->get();
if you already know the value of code, or code will always have some fixed values, then you can use like following:
public function getAll(){
// ...
$loans = Loans::where([['OL_TEMP_APP_NO', $appNo]])->get();
$data = [];
foreach($loans as $loan){
$code = Code::getValue($loan->code);
$data[] = [
'principal' => $loan->principal,
'terms' => $loan->terms,
'code' => ($loan->code == 1) ? 'new' : ( ($loan->code == 2) ? 'processing' : 'approved')
]
}
return $data;
}

Sending Nested Query with Laravel 5.0

I'm sending a series of loops from controller to viewe but I have to return a loop in it.
i want to do something like code
$sor1 = mysql_query("select * from dersler");
while(mysql_fetch_object($sor1)) {
$dersid = $sor1->id;
$sor = mysql_query("select * from gecilendersler where dersid='$dersid'");
while(mysql_fetch_object($sor)) {
echo $sor->dersadi;
}
}
$uyeid =Auth::user()->id;
$dersler = DB::table('dersler')->where('uyeid', $uyeid)->get();
foreach($dersler as $ders) {
$dersid=$ders->id;
}
$saatler = DB::table('saatler')->where('dersid', $dersid)->get();
return view('sayfalar.saatler')
->with([
'dersler' => $dersler,
'saatler' => $saatler
]);
 
I did it this way, but the last record remains in the last line in other records

How can i seed with faker a random id or null in Laravel?

I am trying to seed a parent_id column with a random id of the same table or let it be null.
This i thought it will work:
...
'parent_id' => $faker->boolean() ? Page::all()->random()->id : null,
...
But i get the following error:
You requested 1 items, but there are only 0 items available.
Does anyone know how to do this?
Update1:
Using pseudoanime answer i tried the flowing :
$factory->define(Page::class, function (Faker\Generator $faker) {
...
$parent_id = null;
...
$has_parent = $faker->boolean(50);
Log::debug('$has_parent' . $has_parent);
if ($has_parent) {
$parents = Page::all();
Log::debug('$parents' . count($parents));
if ($parents->isEmpty()) {
Log::debug('isEmpty');
$parent_id = null;
} else {
Log::debug('$parents->random()' . print_r($parents->random(), true));
$parent_id = $parents->random()->id;
}
}
return [
...
'parent_id' => $parent_id,
...
];
}
From what i can see every time it is run Page::all(); return empty.
Any idea why that is?
Try this:
'parent_id' => $faker->boolean(50) ? Page::orderByRaw('RAND()')->first()->id : null,
Essentially we're saying, order by random, get the first and then get it's id.
boolean(50) should give you a 50% chance of true, so 50% false.
$factory->define(Page::class, function (Faker\Generator $faker) {
$ids = Page::pluck('id')->toArray();
return [
'parent_id' = empty($ids) ? null : $faker->optional(0.9, null)->randomElement($ids); // 10% chance of null
];
});
Given "Parent" as the parent model, I do this:
first seed the Parent;
seed the Child table using this code in the factory:
'parent_id' => $faker->optional()->randomElement(App\Parent::all()->pluck('id'))
It works because faker's randomElement() takes an array which you populate with all and only the 'id' values of the parent table.
The optional() faker's modifier does or doesn't put a NULL in the parent_id at random. As stated in faker's GitHub, optional() sometimes bypasses the provider to return a default value instead (which defaults to NULL).
You can also specify the probability of receiving the default value and the default value to return.
NB: you can't do anything if the Parent table isn't seeded. If so, consider the answer of dlnsk.
Your error is happening because your query to page (page:all()->random()) returns no results.
Basically your issue is that you care trying to create a parent to a page before a page is even created.
You can should try something like check if the Page::all() returns a non empty collection, if yes, then get a random element from there, if not, create a new element.
I personally would do something like create a class for null parent element & one that would do null & non-empty parent element.
$factory->defineAs(Page::class, 'ParentPage', function (Faker $faker) {
return [
//the rest of your elements here
'parent_id' => null
];
});
$factory->defineAs(Page::class, 'page', function (Faker $faker) {
$has_parent = $faker->boolean();
if($has_parent) {
$parents = Page::all();
if($parents->isEmpty()) {
$parent_id = factory(Page::class, 'ParentPage')->create()->id;
} else {
$parent_id = $parents->random()->id;
}
}
return [
//the rest of your elements here
'parent_id' => $has_parent? $parent_id : null
];
});
You can create regular pages like factory(Page::class, 'page')->times(50)->create(); in your seeder
The code above is not tested, but the logic should be correct.
public function run()
{
factory(\App\Comment::class, 30)->make()->each(function ($comment){
$comments = Comment::all();
if ($comments->count() == 0) {
$comment->parent = null;
} else {
$rand = random_int(1, $comments->count());
if ($rand >= 2 && $rand <= 5){
$comment->parent = null;
}elseif ($rand >= 12 && $rand <=17){
$comment->parent = null;
}elseif ($rand >= 22 && $rand <= 27){
$comment->parent = null;
}else{
$comment->parent = $rand;
}
}
$comment->save();
});
}

Yii2 display multiple images in gridview row

I want to display multiple images in a gridviews single row. For example: I have table A, Table B and table C.
Table A has my_id.
In Table B my_id is the foreign key. Along with my_id it has c_id.
Table C has c_id which is in reference in Table B.
Table C also has a filepath to display images.
in Table A i have my_id as follows:
1, 2, 3, 4, 5, 6.
In Table B i have my_id as follows.
1 ,1 ,1 ,2 ,3, 3.
In Table B i also have c_id as follows.
1, 2, 3, 4, 5, 6.
In table C my c_id's are:
1, 2, 3, 4, 5, 6. and these id's have filepath associated with each of them. They are different images.
Now my gridview should display 3 different images for my_id because of the foreign key constraints. but it displays only 1 image.
My code is below:
In my model
public function getPictogramsID()
{
$pictogramsID = SdsrefGhsPictograms::find()->where(['sdsref_id' => $this->sdsref_id])->all();
foreach ($pictogramsID as $picID){
return $picID->pictogram_id;
}
}
public function getPictogramPath()
{
$pictogramsID = GhsPictogram::find()->where(['pictogram_id' => $this->getPictogramsID()])->all();
foreach ($pictogramsID as $picID){
$pic = $picID->pictogram_filepath;
}
return $pic;
}
public function getPictogramUrl()
{
//var_dump($this->getPictogramPath()); exit();
return \Yii::$app->request->BaseUrl.'/web'.$this->getPictogramPath() ;
}
my index file grid view image code
[
'label' => 'Hazards',
'format' => 'raw',
'value' => function ($data) {
return Html::img($data->getPictogramUrl(), ['alt'=>'myImage','width'=>'20','height'=>'30']);
},
],
I am also trying to add a bootstrap tool tip to this.. tool tip is displaying successfully but I think the looping is not not done in a correct way so it is repeating my images.
here is my updated gridview code.
[
'label' => 'Hazards',
'format' => 'raw',
'value' => function ($data) {
$images = '';
// append all images
foreach($data->getPictogramName() as $name)
foreach ($data->getPictogramUrl() as $url)
$images = $images.Html::img($url,['alt'=>'','width'=>'30','height'=>'30', 'data-toggle'=>'tooltip','data-placement'=>'left','title' => $name ,'style'=>'cursor:default;']);
return $images;
}
],
You have few logical errors in model and grid view. In all these areas you are dealing with one item instead of three.
In your model
public function getPictogramsID()
{
$ids = [];
$pictogramsID = SdsrefGhsPictograms::find()->where(['sdsref_id' => $this->sdsref_id])->all();
foreach ($pictogramsID as $picID){
$ids[] = $picID->pictogram_id;
}
return $ids;// returning all three ids
}
public function getPictogramPath()
{
$pic = [];
$pictogramsID = GhsPictogram::find()->where(['pictogram_id' => $this->getPictogramsID()])->all();
foreach ($pictogramsID as $picID){
$pic[] = $picID->pictogram_filepath;
}
return $pic;
}
public function getPictogramUrl()
{
$url = [];
foreach($this->getPictogramPath() as $path):
$url[] = \Yii::$app->request->BaseUrl.'/web'.$path;
endforeach;
return $url; // returning al urls
}
Now in you view loop over all urls and append images with each url
[
'label' => 'Hazards',
'format' => 'raw',
'value' => function ($data) {
$images = '';
// append all images
foreach($data->getPictogramUrl() as $url):
$images = $images.Html::img($url, ['alt'=>'myImage','width'=>'20','height'=>'30']);
endforach;
return $images;
},
],

how can I catch a single variable in array of Object in CodeIgniter?

I have probabbly a eal probleme with array . I have a request :
in my model
public function getHomme ($limit ,$offset)
{
$this->db->select('id,nom,prix,nom_marques,nom_path,quantite,semelle_interieure,libelle_fermeture,libelle_style,libelle_talon,libelle_doublure,libelle_semelle,libelle_dessus');
$this->db->from('chaussure');
$this->db->join('gnr_convenir', 'gnr_convenir.identifiant_chaussure = chaussure.id');
$this->db->join('images', 'images.id_chaussure = chaussure.id');
$this->db->join('marques', 'marques.idmarques = chaussure.identifiant_marques');
$this->db->join('fermeture', 'fermeture.idfermeture = chaussure.identifiant_fermeture');
$this->db->join('style', 'style.idstyle = chaussure.identifiant_style');
$this->db->join('talon', 'talon.idtalon = chaussure.identifiant_talon');
$this->db->join('doublure', 'doublure.iddoublure = chaussure.identifiant_doublure');
$this->db->join('materiauSemelle', 'materiauSemelle.idmateriauSemelle = chaussure.identifiant_semelle');
$this->db->join('dessus', 'dessus.iddessus = chaussure.identifiant_dessus');
$this->db->where('identifiant_genre', 1);
$this->db->order_by("id", "desc");
$this->db->limit($limit,$offset);
$query = $this->db->get();
$ligne= $query->num_rows();
if($query->num_rows()>0)
{
foreach($query->result()as $row)
{
$data[] = $row;
}
$data['ligne'] = $ligne;
return $data;
}
so here I need 2 things:
one the object on data and the other is $ligne (number of rows )
so it seems like this when I try to make var_dump($data)
array
'rows' =>
array
0 =>
object(stdClass)[21]
public 'id' => string '89' (length=2)
public 'nom' => string 'zoro' (length=4)
public 'prix' => string '12460.00' (length=8)
1 =>
object(stdClass)[22]
public 'id' => string '87' (length=2)
public 'nom' => string 'adizero' (length=7)
public 'prix' => string '124000.00' (length=9)
'ligne' => int 2
but when I try to write:
var_dump($data['ligne']) in my controller
I have an error message
A PHP Error was encountered
Severity: Notice
Message: Undefined index: ligne
Filename: controllers/client.php
Line Number: 143
null
I need those 2 data in my view, so in my view I thought to use $ligne like this:
$numberLigne = $ligne ;
As a test, could you echo ligne in your model to make sure that your join query is working right? I have no way of knowing without seeing your full table.
Also, any reason why you use:
if($query->num_rows()>0)
Instead of
if($ligne > 0):
Being that you just set that variable?

Resources